user5506560 user5506560 - 6 months ago 18
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:

files.txt,
file2.txt
file3.txt

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:

#!/bin/bash


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



configurer() {


for file in *.txt

do

echo "Processing file .... $file"

orig_file=$file

tmp_file=$orig_file.tmp

cp $orig_file $tmp_file


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

mv $tmp_file directorname/$orig_file



done

}


configurer



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 ?
Regards

Answer

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