how to replace a set of lines in a file with anoth

2019-08-20 05:46发布

问题:

how to replace a set of lines in a file with another set of lines in unix ?

#!/usr/bin/ksh
export text1='log_file=$LOG_PATH${UNISON_JOB}".log"'
export text2='\. \$\{env_path\}set_test_log_file\.ksh'
export text3='log_file\=\$LOG_PATH\$\{UNISON_JOB\}\"\.log\"'

echo $text1
echo $text2
echo $text3

for file in `grep -il ${text1} SANDEEP`
do
sed 's/${text3}/${text2}/g' $file > /$file.tmp
mv /$file.tmp $file
echo $file
done

i tried the above code but its not working . its kshell .here sandeep is the file name i m searching.

回答1:

The reason why this doesn't work is because you use single qoutes for the sed command.

The sed command is trying to replace the literal text ${text3} with ${text2}. What you want it to to is to replace the value of $text3 with the value of $text2.

In order to use variables in the sed expression you need to use double quotes.

Another tip: if you do not need the temporary file you might as well use the -i option of sed to edit the file in place.

Hope this helps.



回答2:

For sed with the quote, I like to write whole command into a file, then execute this file: something like this:

echo "s/${text1}/${text2}/g" > a.sed
sed -f a.sed < inputFile > tmp && mv tmp inputFile
rm -f a.sed

that will save a lot of trouble to deal with those quote thing.



标签: shell unix