user5506560 user5506560 - 1 year ago 84
Linux Question

Unix script / replace string in file from variable and move into another directory

I'm trying to do a script which find specific string in .txt files and replace by variable. I don't want to change original files but do the copies and then move into another (specific) directory. Let's assume 3 .txt files:


First step is to find string "string1" and "string2" in all .txt files and do the copies (eg. tmp files).
Second is to replace a string by variable $1 and $2 (working on tmp files).
Then move all of them to 'directoryname' directory.

That's what I'v got:


echo "$1 - first parameter"
echo "$2 - second"

configurer() {

for file in *.txt


echo "Processing file .... $file"



cp $orig_file $tmp_file

sed "s/string1/$1/g;s/string2/$2/g" $tmp_file

mv $tmp_file directorname/$orig_file




echo "Done ..."

It's almost correct, (correct move into another directory, do the tmp files), but sed function doesn't work as it should and I have no idea why. Could anyone take a look ?

Answer Source

try below sed, its always problem with sed with variable

sed -i -e 's/string1/'"$1"'/g'  -e 's/string2/'"$2"'/g' $tmp_file 

let me know if it works

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download