简体   繁体   English

在Shell脚本中使用sed将字符串替换为另一个子字符串

[英]Replace a string with another substring using sed in shell script

For every line except the first line in my file,I want to check if a string already exists . 对于文件中第一行以外的每一行,我想检查一个字符串是否已经存在。 If it does, then do nothing. 如果是这样,则什么也不做。 Otherwise, append the string to the line 否则,将字符串附加到该行

For ex - there are foll 3 lines in my file 例如-我的文件中有3行

line1 : do_not_modify

line2-string-exists

line3

I want to append -string-exists to only those lines in the file which does not have that string appended to them(Ignore the first line) 我只想将-string-exists附加到文件中没有附加该字符串的那些行(忽略第一行)

the output should be - 输出应为-

line1 : do_not_modify

line2-string-exists

line3-string-exists

Please tell me How will I do it using sed ? 请告诉我如何使用sed Or is it possible to do with awk ? 还是可能与awk

$ cat data
line1 : do_not_modify
line2-string-exists
line3

$ sed '1!{/-string-exists/! s/$/-string-exists/}' data
line1 : do_not_modify
line2-string-exists
line3-string-exists

or using awk : 或使用awk

$ awk '{if(NR!=1 && ! /-string-exists/) {printf "%s%s", $0, "-string-exists\n"} else {print}}' data
line1 : do_not_modify
line2-string-exists
line3-string-exists

You can use this sed command: 您可以使用以下sed命令:

sed -E '/(do_not_modify|-string-exists)$/!s/$/-string-exists/' file

line1 : do_not_modify
line2-string-exists
line3-string-exists

Or using awk : 或使用awk

awk '!/(do_not_modify|-string-exists)$/{$0 = $0 "-string-exists"} 1' file

Assuming the string doesn't contain any RE metacharacters: 假设字符串不包含任何RE元字符:

$ awk 'BEGIN{s="-string-exists"} (NR>1) && ($0!~s"$"){$0=$0 s} 1' file
line1 : do_not_modify
line2-string-exists
line3-string-exists

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

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