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

use*_*172 59 sed

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

some text here
blah blah 123
another new line
some other text as well
another line
Run Code Online (Sandbox Code Playgroud)

我想删除除包含字符串'text' 字符串'blah'的那些行之外的所有行,所以我的输出文件如下所示:

some text here
blah blah 123
some other text as well
Run Code Online (Sandbox Code Playgroud)

任何提示如何使用sed

pot*_*ong 99

这可能对你有用:

sed '/text\|blah/!d' file
some text here
blah blah 123
some other text as well
Run Code Online (Sandbox Code Playgroud)

  • @lovedynasty如果你的意思是*在行尾*,你应该使用`$`:`'/ text $\| blah $ /!d'` (3认同)

Jon*_*ler 16

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

sed -n -e '/text/{p;n;}' -e '/blah/{p;n;}' your_data_file
Run Code Online (Sandbox Code Playgroud)

-n默认情况下,手段不打印.第一种模式搜索"文本",如果匹配则打印它并跳到下一行; 第二种模式对'blah'也是一样的.如果'n'不在那里,则包含'text and blah'的行将被打印两次.虽然我可以使用just -e '/blah/p',但对称性更好,特别是如果你需要扩展匹配单词列表.

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

sed -r -n -e '/text|blah/p' your_data_file
Run Code Online (Sandbox Code Playgroud)

  • 如果sed不支持`-r`,它可能也不支持`{}`.这适用于旧的seds:`sed'/ text\| blah /!d'file` (3认同)

Avi*_*Raj 6

你可以通过awk简单地完成它,

$ awk '/blah|text/' file
some text here
blah blah 123
some other text as well
Run Code Online (Sandbox Code Playgroud)