不包含特定字符串的删除行

我是 sed的新手,我有以下问题。在这个例子中:

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

我想删除除了包含字符串‘ text’还有或字符串‘ brah’的行之外的所有行,因此我的输出文件如下所示:

some text here
blah blah 123
some other text as well

有什么提示可以使用 sed实现这一点吗?

95176 次浏览

您希望只打印那些与“ text”或“ brah”(或两者都是)匹配的行,其中“ and”和“ or”之间的区别是相当重要的。

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

-n表示默认情况下不打印。第一个模式搜索“ text”,如果匹配就打印它,然后跳到下一行; 第二个模式对“ brah”执行相同的操作。如果“ n”不在那里,那么包含“ text and brah”的行将被打印两次。虽然我可以只使用 -e '/blah/p',对称性更好,特别是如果你需要扩展匹配的单词列表。

如果您的 sed版本支持扩展正则表达式(例如,GNU sed支持,使用 -r) ,那么您可以将其简化为:

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

这可能对你有用:

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

你可以简单地通过 awk 来做,

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

你在找 grep吗? 下面是一个查找不同文本的示例。

cat yourfile.txt | grep "text\|blah"