2012-03-02 263 views
48

我是sed的新手,我有以下问题。在这个例子中:sed删除行不包含特定字符串

some text here 
blah blah 123 
another new line 
some other text as well 
another line 

我要删除除包含任何字符串“文本” 或字符串“嗒嗒”的所有行,所以我的输出文件看起来像这样:

some text here 
blah blah 123 
some other text as well 

任何提示如何使用sed来完成?

+3

必由之路答案用sed? grep会很容易地做到这一点。 – Tim 2012-03-02 23:48:06

回答

11

您只想打印与'text'或'blah'(或两者)匹配的行,'and'和'or'之间的区别非常重要。

sed -n -e '/text/{p;n;}' -e '/blah/{p;n;}' your_data_file 

-n表示默认情况下不打印。第一种模式搜索'文本',如果匹配则打印它并跳到下一行;第二种模式对'blah'也一样。如果'n'不在那里,那么包含'text和blah'的行将被打印两次。尽管我只能使用-e '/blah/p',但对称性更好,尤其是在需要扩展匹配单词列表的情况下。

如果您的sed版本支持扩展正则表达式(例如,GNU sed确实,与-r),那么你就可以简化到:

sed -r -n -e '/text|blah/p' your_data_file 
+3

如果sed不支持'-r',它可能也不会支持'{}'。这应该适用于较老的seds:'sed'/ text \ | blah /!d'file' – 2012-03-03 01:10:54

+0

'{...}'命令分组是在第7版UNIX版本的'sed';我想不出你怎么会遇到一个没有支持的版本。 – 2012-03-03 03:10:03

79

这可能会为你工作:

sed '/text\|blah/!d' file 
some text here 
blah blah 123 
some other text as well 
+0

谢谢,这是有效的。 – user1246172 2012-03-04 22:04:28

+1

我怎样才能例如指定文本或等值只能出现在最后一列? – discipulus 2014-05-14 12:27:52

+2

@lovedynasty如果你的意思是*在行尾*,你应该使用'$':''/ text $ \ | blah $ /!d'' – Melebius 2015-02-12 11:58:49

5

你可以简单地做它通过AWK,

$ awk '/blah|text/' file 
some text here 
blah blah 123 
some other text as well