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
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 for your piece of code
#!/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 -i -e 's/string1/'"$1"'/g' -e 's/string2/'"$2"'/g' $tmp_file
mv $tmp_file directorname/$orig_file
done }
configurer $1 $2
echo "Done ..."
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.