2011-12-01 35 views
0

這是一個測試文件:有什麼方法可以通過sed刪除模式的第一次出現?

xxx 
hello 
hello 
others 

我想用SED:

sed -i '/hello/d' the_test_file 

這將刪除所有行包含「你好」,所以如何只是刪除第一行包含「你好」 ?

我認爲sed不能做到這一點,但用perl我可以。它就像:

perl -00 -pe "s/hello//" the_test_file > /tmp/file && mv /tmp/file the_test_file 
+0

請停止改變的問題。如果您不斷更改,我的回答將不準確。 – mezzie

回答

2

顯示文件的原始內容。

cat the_test_file 
1 
2 
3 
popo 
hello 1 
hello 2 
others 

顯示結果運行sed命令

sed -e '0,/^hello/{//d;}' the_test_file 
1 
2 
3 
popo 
hello 2 
others 

到最後回答你的問題

注後:感謝jaypal

sed -i"bak" -e '0,/^hello/{//d;}' the_test_file 
+0

這會刪除'hello'之前的行。根據我的測試數據進行測試。 –

+0

對不起,他一直在改變這個問題,原來的測試數據不像現在這樣。 – mezzie

+2

no biggie ..'sed -i「bak」'0,/^hello/{// d;}'ff'將消除移動文件的第二遍。 '-i「bak」'將備份原始文件並更新當前文件。 :) –

0

awk解決方案:

$ cat file 
something 
hello 1 
else 
hello 2 
others 
hello 3 

$ awk '/hello/ && ++c==1{next}1' file 
something 
else 
hello 2 
others 
hello 3 
0

這是卓有成效的(但不容易概括):

$ sed -e '1,/hello/p' -e '1,/hello/d' -e '/hello/d' <<! 
> xxx 
> hello 
> hello 
> others 
! 
xxx 
hello 
others 
$ 

的邏輯是從第1行的行打印到含有「你好」的第一行;然後刪除這些行(所以自動打印不會發生);此後,只需刪除與「hello」匹配的行。

1

要刪除第一聲問候

sed -e "/hello/ N;n;d;" the_test_file 

刪除第二個招呼

sed -e "/hello/ N;n;n;d;" the_test_file 

如果有超過2線你好連續,並希望保留的第一聲問候,並刪除其餘

sed -e ":loop" -e "/hello/ N; s/\(hello.*\)\n\(hello.*\)/\1/" -e "t loop" the_test_file 

如果連續超過2行hello,並且想保留th Ë最後hello,它只

sed -e ":loop" -e "/hello/ N; s/\(hello.*\)\n\(hello.*\)/\2/" -e "t loop" the_test_file 

the_test_file

xxx 
hello1 
hello2 
hello3 
others 
相關問題