Find line using variable string, replace whole line with another line generated from nested loop

ぐ巨炮叔叔 提交于 2019-12-11 08:02:57

问题


I have a script that begins with:

sed 's!'$1'!'$2'!g' file.txt > new.txt ;

$1 and $2 are variable and a third variable $3 is used later in the script, the script is executed in this format:

./script.sh variable variable2 variable3

The next part of the script adds the third variable to a text file:

sed "s!><!> $3 <!4" newer.txt > newest.txt

What I want to do now is use the output from "newest.txt" (which is one line and includes characters like /<>"/ as it's in html) and replace a line in another file which is identified using variable2 as the match.

This is what I have but it doesn't seem to replace the whole line, only part.

for i in `cat newest.txt` ;
do
sed '/$2/s/.*/$i/' new.txt > final.txt
done

I'm on Solaris which doesn't allow the -i switch when using sed. Sed, awk or bash would be preferable.

Thanks in advance!


回答1:


Using r command to read from a file will be robust as it won't break based on content of file or multiple line file input

sed -e "/$2/r newest.txt" -e "/$2/d" new.txt > final.txt

or

sed -e "/$2/r newest.txt" -e '//d' new.txt > final.txt

Thanks to @mklement0 for pointing out that content of replacement can affect the outcome and that we can reuse pattern for d command:


Illustrating the various cases:

$ cat ip.txt 
foo
bar
baz
123

$ s='ba'
$ echo 'XYZ' > f1
$ r=$(<f1)

$ sed "/$s/s/.*/$r/" ip.txt 
foo
XYZ
XYZ
123

$ sed "/$s/c$r" ip.txt 
foo
XYZ
XYZ
123

$ sed -e "/$s/r f1" -e '//d' ip.txt 
foo
XYZ
XYZ
123

If replacement string contains characters like /

$ echo '/XYZ/' > f1
$ r=$(<f1)

$ sed "/$s/s/.*/$r/" ip.txt 
sed: -e expression #1, char 11: unknown option to `s'

$ sed "/$s/c$r" ip.txt 
foo
/XYZ/
/XYZ/
123

$ sed -e "/$s/r f1" -e '//d' ip.txt 
foo
/XYZ/
/XYZ/
123

And for multiple line:

$ echo -e 'XYZ\nABC' > f1
$ r=$(<f1)

$ sed "/$s/s/.*/$r/" ip.txt 
sed: -e expression #1, char 12: unterminated `s' command

$ sed "/$s/c$r" ip.txt 
sed: -e expression #1, char 10: unknown command: `A'

$ sed -e "/$s/r f1" -e '//d' ip.txt 
foo
XYZ
ABC
XYZ
ABC
123

Note: Some sed versions might need sed "/$s/c\\$r" ip.txt where c\ is the usage of c command. Inside double quotes \ needs to be escaped



来源:https://stackoverflow.com/questions/40699553/find-line-using-variable-string-replace-whole-line-with-another-line-generated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!