我对sed
很陌生,我有一个以下问题。在这个例子中:
some text here
blah blah 123
another new line
some other text as well
another line
我想要删除除包含字符串'text'或者字符串'blah'的行以外的所有行,使得输出文件如下所示:
some text here
blah blah 123
some other text as well
有什么提示可以使用sed
来完成这个任务吗?我对sed
很陌生,我有一个以下问题。在这个例子中:
some text here
blah blah 123
another new line
some other text as well
another line
我想要删除除包含字符串'text'或者字符串'blah'的行以外的所有行,使得输出文件如下所示:
some text here
blah blah 123
some other text as well
有什么提示可以使用sed
来完成这个任务吗?这个可能适合你:
sed '/text\|blah/!d' file
some text here
blah blah 123
some other text as well
$
:'/text$\|blah$/!d'
。 - Melebius/
。在替换命令中,可以将其设置为任何分隔符,例如s#...#...#
。但是,在用于匹配时,第一个分隔符必须加引号,例如将分隔符设置为#
,使用\#match#d
来删除匹配的行。 - potong您想打印出与“text”或“blah”(或两者都匹配)相匹配的行,其中“and”和“or”的区别非常关键。
sed -n -e '/text/{p;n;}' -e '/blah/{p;n;}' your_data_file
-n
的意思是默认不进行打印。第一个模式用于搜索“text”,如果匹配则打印并跳到下一行;第二个模式对“blah”执行同样的操作。如果没有使用“-n”,则包含“text和blah”的行将被打印两次。虽然我本可以使用 -e '/blah/p'
,但对称性更好,特别是在需要扩展匹配单词列表时。如果您的sed
版本支持扩展正则表达式(例如GNU sed
支持-r
),则可以简化为:sed -r -n -e '/text|blah/p' your_data_file
-r
,那么它可能也不支持 {}
。对于旧的 sed,这应该可以工作:sed '/text\|blah/!d' file
。该命令的意思是从文件中删除所有不包含 "text" 或 "blah" 的行。 - glenn jackmana
和a b
,以下命令只会打印第一行输入echo -e 'a\na b' | sed -n -e '/b/{p;n;}' -e '/a/{p;n;}'
。但是如果我改变表达式的顺序,该命令将打印两行输入echo -e 'a\na b' | sed -n -e '/a/{p;n;}' -e '/b/{p;n;}'
。 - JamesThomasMoonsed
大师。我想知道是否可以找到旧的、鲜为人知但仍然活跃的Unix工具大师邮件列表。 - JamesThomasMoon你可以简单地通过awk来完成它,
$ awk '/blah|text/' file
some text here
blah blah 123
some other text as well
你正在寻找 grep
吗?
以下是查找不同文本的示例。
cat yourfile.txt | grep "text\|blah"