【问题标题】:grep for a line with a specific wordsgrep 查找包含特定单词的行
【发布时间】:2014-11-18 17:19:21
【问题描述】:

我有一个文件 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.

请帮忙。 谢谢你

【问题讨论】:

    标签: shell unix grep


    【解决方案1】:

    使用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.
    

    【讨论】:

    • 这是你的决定,但我会避免使用多个管道grep 来完成这样一个简单的任务。想象一下,如果您有 10 个关键字,那么您将需要 10 个管道 grep 命令。如果你想避免前瞻,awk 是在这里使用的正确命令。
    • 您可以使用:awk '/[bB]atman/&&/[cC]ity/&&/[gG]otham/&&!/joker/' file/ 用于 awk 中的正则表达式分隔符。
    • 您可以使用:grep -iP '(?=.*?\bbatman\b)(?=.*?\bcity\b)(?=.*?\bgotham\b)(?!.*?\bjoker\b)' batman.txt
    • 最后一个请求:你有什么书或网站可以让我学习这些命令吗?如果您能提出一些建议,我将不胜感激:)
    • 这基本上是在学习正则表达式,我知道的最好的网站是regular-expressions.info
    【解决方案2】:

    你为什么不尝试管道到另一个 grep?

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

    它更简单。你甚至不需要为此学习正则表达式。

    【讨论】:

    • -wexact word match
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多