bash sed- 删除不包含模式的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27734189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:06:12  来源:igfitidea点击:

sed- delete line that doesn't contain a pattern

bashsed

提问by buydadip

I'm surprised that I can't find a question similar to this one on SO.

我很惊讶我在 SO 上找不到与此类似的问题。

How do I use sed to delete all lines that do not contain a specific pattern.

如何使用 sed 删除所有不包含特定模式的行。

For example, I have this file:

例如,我有这个文件:

cat kitty dog
giraffe panda
lion tiger

I want a sed command that, when called, will delete all lines that do not contain the word cat:

我想要一个 sed 命令,当调用它时,将删除所有不包含单词的行cat

cat kitty dog

回答by Amit Verma

This will do:

这将:

sed -i '/cat/!d' file1.txt

To force an exact match:

强制精确匹配:

sed -i '/\<cat\>/!d' file1.txt

or

或者

sed -i '/\bcat\b/!d' file1.txt

where \<\>& \b\bforce an exact match.

where \<\>&\b\b强制精确匹配。

回答by Kent

So your requirement would be "give me all lines containing string cat". then why not just simply using grep:

所以你的要求是“给我所有包含字符串的行cat”。那么为什么不简单地使用grep

grep cat file

回答by Jotne

You can use this awk

你可以用这个 awk

awk '/cat/' file

回答by Denio Mariz

to see all lines containg word 'cat' (as pointed by Kent):

查看包含单词“cat”的所有行(如 Kent 所指出的):

grep cat file

to see all lines NOT containg word 'cat':

查看所有不包含单词“cat”的行:

grep -v cat file