【问题标题】:How to reverse the output of the grep command?如何反转 grep 命令的输出?
【发布时间】:2017-06-30 09:02:54
【问题描述】:

我对 grep 命令有一个问题。在我调用的脚本中我使用:

   "ServicePassword":fooooooooooo
   "ServiceUserName":barrrrrrrrr
grep -E '"ServiceUserName"|"ServicePassword"' >> user.txt

但在 user.txt 文件中,我将首先获得“ServicePassword”:fooooooooooo 然后是“ServiceUserName”:barrrrrrrrr 我如何使用 grep 命令将其反转以在 user.txt 文件中获取第一个 ServiceUserName 然后是 ServicePassword 输出?我只需要这个序列。我尝试改变:

grep -E '""ServicePassword""|"ServiceUserName"' >> user.txt

什么都没有......也许存在更好的解决方案?

【问题讨论】:

    标签: linux bash shell grep


    【解决方案1】:

    grep 只是过滤器,man grep : print lines matching a pattern,要更改顺序必须使用另一个工具,因为只有两个项目可能添加 |sort|sort -r(反向排序)会有所帮助。

    grep -E '"ServiceUserName"|"ServicePassword"' | sort -r >> user.txt
    

    【讨论】:

    • 它可以工作,但在大文件上速度很慢,因为你在 grep 之后排序
    • @sebadagostino,感谢您的评论,您能解释一下您的意思,在 grep 之前,大文件排序会更快吗?
    • 嗨 Nahuel,我并不是说在 greping 之前进行排序会更快。我对一个大日志文件进行了 grep + 排序,这需要很长时间,因为在完成整个 grep 之后进行排序需要很长时间。我认为它有效,但如果我更频繁地使用它,我会深入研究一个性能更高的解决方案。
    • 正如我在回答中所说,在这种特殊情况下可以使用排序,因为只有两个项目。其他答案的性能并不高,他们需要读取最昂贵的整个文件
    • 一种优化可以是逐行读取并在一个命令中找到两种模式后停止perl -ne '$pwd=$_ if/"ServicePassword"/;$user=$_ if/"ServiceUserName"/;exit print$user.$pwd if$user&&$pwd'
    【解决方案2】:

    您可以使用和改编下面的tac command

    $ cat test.txt
    "ServicePassword":fooooooooooo
    "ServiceUserName":barrrrrrrrr
    
    $ egrep '"ServicePassword"|"ServiceUserName"' test.txt | tac
    "ServiceUserName":barrrrrrrrr
    "ServicePassword":fooooooooooo
    

    【讨论】:

    • 不需要以cat test.txt开头-只需egrep '"ServicePassword"|"ServiceUserName"' test.txt | tac > user.txt
    【解决方案3】:

    使用awk:

    awk '/ServicePassword/{pwd=$0};/ServiceUserName/{user=$0};
         END{printf pwd; print user}' 
    

    【讨论】:

      【解决方案4】:

      使用tac(与cat相反)

      grep -E '"ServiceUserName"|"ServicePassword"' | tac >> user.txt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-06
        • 1970-01-01
        • 1970-01-01
        • 2021-03-29
        相关资源
        最近更新 更多