【问题标题】:Grep highlight a pattern other than the searched oneGrep 突出显示除搜索到的模式之外的模式
【发布时间】:2013-10-16 12:46:49
【问题描述】:

我正在使用 grep 搜索一些日志文件,我的日志条目如下所示:

[2013-10-16 14:39:17] {"email":"email@host.com", "tel":"123456789", "address":"some address", "status":"0"}

(这是一个示例,每个条目都有很多数据)

我想要做的是:用一种模式过滤并突出显示另一种模式,例如我过滤status=1

cat log | grep 'status":1'

这很好用,并输出如下内容:

[2013-10-16 14:39:17] {"email":"email@host.com", "tel":"123456789", "address":"some address", "status ":"1"}

我想要做的是在输出中突出显示电子邮件以具有如下内容:

[2013-10-16 14:39:17] {"email":"email@host.com", "tel":"123456789", "address":"一些地址", "状态":"1"}

注意,我只想突出显示电子邮件,而不是过滤!

这可能吗?

谢谢

【问题讨论】:

  • 不清楚为什么你想这样做?

标签: bash grep


【解决方案1】:

只需 grep 再次为您要突出显示的模式:

cat log | grep 'status":"1' | grep '"email":"[^"]*"'

【讨论】:

    【解决方案2】:

    仅出于突出显示的目的,您可以查看https://github.com/nicoulaj/rainbow

    这里列出了其他一些荧光笔:https://stackoverflow.com/a/4269167/363281

    【讨论】:

    • 我无权安装任何东西,只是检查一些日志以进行调试...
    【解决方案3】:

    假设你已经突出显示你会做的:

    $ grep -e '"email":"[^"]*"' -e '"status":"1"'  file
    

    如果您尚未设置突出显示,请使用 --color 选项:

    $ grep --color=auto -e '"email":"[^"]*"' -e '"status":"1"'  file
    

    这将按1 的状态'过滤并突出显示所有电子邮件和状态'。如果您只想突出显示电子邮件,那么:

    $ grep '"status":"0"' file | grep '"email":"[^"]*"'
    

    【讨论】:

      【解决方案4】:

      另外,尝试操作使用awk 过滤的文本。像这样的文件

      $ cat test.txt
      [2013-10-16 14:39:17] {"email":"email1@host.com", "status":"1"}
      [2013-10-16 14:39:17] {"email":"email2@host.com", "status":"0"}
      [2013-10-16 14:39:17] {"email":"email3@host.com", "status":"1"}
      [2013-10-16 14:39:17] {"email":"email4@host.com", "status":"0"}
      [2013-10-16 14:39:17] {"email":"email5@host.com", "status":"1"}
      [2013-10-16 14:39:17] {"email":"email6@host.com", "status":"0"}
      [2013-10-16 14:39:17] {"email":"email7@host.com", "status":"1"}
      

      试试这个命令

      cat test.txt | grep \"status\":\"1\" | awk '{print "\033[32m",$3,"\033[0m",$4}'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-11
        • 1970-01-01
        • 2018-01-09
        • 1970-01-01
        • 1970-01-01
        • 2010-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多