2017-06-16 49 views
0

我有一個包含一些行的文件。Linux Bash:如果條件匹配,則添加前綴到行

我想添加一個前綴到這些行,如果它包含一些關鍵詞。

我該怎麼做?謝謝!

我想補充"###"到線, 「Hello」 在行的開頭:

當前這個文件有:

This is the beginning. 
Hello I am Simon. 
This is a simple line; 
Hello Mike. 
This is another line. 

我想改變此文件到:

This is the beginning. 
###Hello I am Simon. 
This is a simple line; 
###Hello Mike. 
This is another line. 

回答

5

sed程序會爲你做。對於例如,你貼:

$ sed 's/^Hello/###Hello/' <file> 
+2

請記住使用'sed -i'將更改寫入文件並轉義特殊字符。 – jgmh

+3

可能更習慣於寫'sed'/^Hello/s/^/### /''。 –

1

和awk的解決方案是:

awk '{if($1=="Hello"){print "###"$0 ; } else {print $0}}' <file> 

但我認爲SED是這種情況下,更好的辦法。

+3

寫'awk'/^Hello/{printf「###」}更加尷尬(也就是說更習慣)1'輸入文件' –

相關問題