繁体   English   中英

如果在shell脚本中找不到,如何替换行(如果找到)或追加到文件末尾?

[英]How to replace line if found or append to end of file if not found in shell script?

我提到了帖子:

sed命令:如果存在则如何替换,只需插入?

https://superuser.com/questions/590630/sed-how-to-replace-line-if-found-or-append-to-end-of-file-if-not-found

但是,所有解决方案似乎都没有用。 有人可以解释为什么吗?

我只是通过制作特定文件在终端上执行命令

sed -e 's/^avpgw/new text/' -e t -e 's/^av/new text/' -e t -e 's/^/new text/' file

sed '/^FOOBAR=/{h;s/=.*/=newvalue/};${x;/^$/{s//FOOBAR=newvalue/;H};x}' infile

测试用例:

$ cat > file
match
miss

解决方案:

$ awk 'sub(/match|$/,"hit")' file
hit
misshit

即。 替换第一个match或记录结尾的$ ,以先到者为准。

sed

sed '/match/{s/match/replace/g;p;D}; /match/!{s/$/replace/g;p;D}' file

测试:

$ cat file
some text... match ... some text
some text only here...
..... here also...

$ sed '/match/{s/match/replace/g;p;D}; /match/!{s/$/replace/g;p;D}' file
some text... replace ... some text
some text only here...replace
..... here also...replace

注意:使用-i在适当位置编辑文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM