我是新手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?
Answers:
这可能对您有用:
sed '/text\|blah/!d' file
some text here
blah blah 123
some other text as well
$:'/text$\|blah$/!d'
/。这可以被设置为在替换命令例如任何定界符s#...#...#用于然而,当为第一分隔符匹配必须被引用例如组定界符#使用\#match#d删除线相匹配的。
您只想打印与“文本”或“ blah”(或两者)匹配的行,其中“ and”和“ or”之间的区别非常关键。
sed -n -e '/text/{p;n;}' -e '/blah/{p;n;}' your_data_file
该-n方法默认情况下不打印。第一个模式搜索“文本”,如果匹配则将其打印并跳至下一行;第二种模式对“ blah”的作用相同。如果“ n”不存在,则包含“ text and blah”的行将被打印两次。尽管我可以使用just -e '/blah/p',但是对称性更好,尤其是当您需要扩展匹配单词的列表时。
如果您的sed支持版本支持扩展的正则表达式(例如,GNU支持sed,使用-r),则可以将其简化为:
sed -r -n -e '/text|blah/p' your_data_file
-r则可能也不支持{}。这应该适用于较老的sed:sed '/text\|blah/!d' file
{ ... }命令的分组在的第七版UNIX版本中sed; 我不认为您会遇到一个不支持的版本。
sed -n -e '/keep-this/p' -e '/keep-that/p' -e '/keep-those/p'。无需复合命令。“行将被打印两次”没有问题。此外,在我的情况下,添加额外的命令n在{p;n;}将放弃第一个表达式匹配。这可能是由于特定的输入字符串引起的。但是这个答案确实帮助我找到了地方!
"keep-this" he said, and "keep-that", not to mention "keep-those"。您的版本将打印该行三遍;我只有一次。这取决于您所需的输出。如果要单行打印三遍,则解决方案很好。如果没有,那么就有些不足了。
a和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;}'。
您可以通过awk轻松完成操作,
$ awk '/blah|text/' file
some text here
blah blah 123
some other text as well