使用sed删除除结束模式之外的行范围

时间:2013-05-19 09:43:04

标签: awk sed

input.txt

blah1
blah2
start_pattern
blah3
blah4
blah5
end_pattern
blah6
blah7

我希望input.txt成为:

blah1
blah2
end_pattern
blah6
blah7

我尝试了以下操作,但它没有用。

sed -i "/start_pattern/, /end_pattern/{$!d}" input.txt

2 个答案:

答案 0 :(得分:6)

This question处理您的问题:

$ sed '/start_pattern/,/end_pattern/{/end_pattern/!d}' foo.txt
blah1
blah2
end_pattern
blah6
blah7

答案 1 :(得分:6)

sed是单行简单替换的绝佳工具。对于任何其他文本操作,只需使用awk来获得更清晰,更简单,更易于扩展的解决方案:

$ awk '/start_pattern/{f=1} /end_pattern/{f=0} !f;' file
blah1
blah2
end_pattern
blah6
blah7

另见:

$ awk '/start_pattern/{f=1} !f; /end_pattern/{f=0}' file
blah1
blah2
blah6
blah7

$ awk '!f; /start_pattern/{f=1} /end_pattern/{f=0}' file
blah1
blah2
start_pattern
blah6
blah7

$ awk '/start_pattern/{f=1} /end_pattern/{f=0} f;' file
start_pattern
blah3
blah4
blah5

$ awk '/start_pattern/{f=1} f; /end_pattern/{f=0}' file
start_pattern
blah3
blah4
blah5
end_pattern

$ awk 'f; /start_pattern/{f=1} /end_pattern/{f=0}' file
blah3
blah4
blah5
end_pattern