2016-06-01 116 views
1

除了我的文件中的第一行外,我想檢查一個字符串是否已經存在。如果是這樣,那就什麼都不要做。否則,將字符串到行在shell腳本中使用sed替換另一個子字符串

對於前 - 有FOLL 3個系在我的文件

line1 : do_not_modify 

line2-string-exists 

line3 

我要追加-string-exists只在文件中的行不具有該字符串追加到他們(忽略的第一行)

輸出應該是 -

line1 : do_not_modify 

line2-string-exists 

line3-string-exists 

請告訴我它使用sed我將如何做?或者是否有可能與awk

+2

可以使用'sed'或'awk'來解決問題。你試過什麼了? –

回答

4
$ 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 

或使用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 
+0

謝謝!我的命令缺少花括號。它現在正在工作 – Manisha

1

您可以使用此命令sed

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

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

或者使用awk

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

我不認爲輸入文件中實際存在「do_not_modify」。 –

+1

是的,可能是OP會希望'awk'NR> 1 &&!/ - string-exists $/{$ 0 = $ 0「-string-exists」} 1'file' – anubhava

0

假設字符串不包含任何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