我有一个文件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.
请帮忙。 谢谢
答案 0 :(得分:3)
使用grep -P
和前瞻性正则表达式,因为您的关键字可以按任何顺序出现:
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 :(得分:2)
为什么你没有尝试使用另一个grep?
grep -iw batman file | grep -iw gotham | grep -iw city
它简单得多。你甚至不需要为此学习正则表达式。