搜索包含特定单词的行 - 使用grep命令

3
我有一个文件 Batman.txt:
Batman lives in Gotham City.
In Gotham city batman is a vigilante
Gotham city has many criminals.
Batman and Joker live in Gotham city.
Superman and batman are very friendly, but batman is always prepared for 
bad events unlike superman.
Superman lives in Metropolis city.
Batman has visited Metropolis city a couple of times.

我希望将包含“蝙蝠侠”、“哥谭市”和“城市”的行分开。即:
Batman lives in Gotham City.
In Gotham city batman is a vigilante
Batman and Joker live in Gotham city.

到目前为止,我有这个:

grep -E -i "batman|gotham|city" batman.txt

但它没有提供必要的输出。我得到了其他不需要的行。
输出是:
Batman lives in Gotham City.
In Gotham city batman is a vigilante
Gotham city has many criminals.
Batman and Joker live in Gotham city.
Superman and batman are very friendly, but batman is always prepared for 
Superman lives in Metropolis city.
Batman has visited Metropolis city a couple of times.

请帮忙。谢谢。

2个回答

3
使用 grep -P 和 lookahead 正则表达式,因为您的关键字可以以任何顺序出现:
grep -iP '(?=.*?\bbatman\b)(?=.*?\bcity\b)(?=.*?\bgotham\b)' file
Batman lives in Gotham City.
In Gotham city batman is a vigilante
Batman and Joker live in Gotham city.

或者使用awk:

awk '/[bB]atman/&&/[cC]ity/&&/[gG]otham/' file
Batman lives in Gotham City.
In Gotham city batman is a vigilante
Batman and Joker live in Gotham city.

1
这是你的决定,但我会避免在如此简单的任务中使用多个管道grep。想象一下,如果你有10个关键字,那么你将需要10个管道grep命令。如果你想避免前瞻awk是正确的命令在这里使用。 - anubhava
2
你可以使用以下命令:awk '/[bB]atman/&&/[cC]ity/&&/[gG]otham/&&!/joker/' file,在awk中,/用作正则表达式的分隔符。 - anubhava
2
你可以使用以下命令:grep -iP '(?=.*?\bbatman\b)(?=.*?\bcity\b)(?=.*?\bgotham\b)(?!.*?\bjoker\b)' batman.txt - anubhava
1
最后一个请求:你有没有一些书或网站可以教我这些命令?如果你能给我推荐一些,我会非常感激的 :) - gkmohit
1
这基本上是关于正则表达式的学习,我知道的最好网站就是 http://regular-expressions.info。 - anubhava
显示剩余3条评论

2

为什么你不尝试将输出通过管道传递给另一个grep命令?

grep -iw batman file | grep -iw gotham | grep -iw city

这很简单。您甚至不需要学习正则表达式。


1
-w 表示 精确单词匹配 - Shiplu Mokaddim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接