简体   繁体   English

如何反转grep命令的输出?

[英]How to reverse the output of the grep command?

i have one problem with grep command.我对 grep 命令有一个问题。 in my called script i use:在我调用的脚本中,我使用:

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

but in user.txt file i will get first "ServicePassword":fooooooooooo then "ServiceUserName":barrrrrrrrr How can i use grep command to reverse it to get first ServiceUserName then ServicePassword output in user.txt file ?但在 user.txt 文件中,我将首先获得“ServicePassword”:fooooooooooo 然后“ServiceUserName”:barrrrrrrrr 我如何使用 grep 命令反转它以在 user.txt 文件中获得第一个 ServiceUserName 然后 ServicePassword 输出? I need it only this sequence.我只需要这个序列。 i try to change:我尝试改变:

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

and nothing.... maybe exist a better solution?什么都没有......也许存在更好的解决方案?

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

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

You can use and adapt the tac command below:您可以使用和调整以下tac 命令

$ cat test.txt
"ServicePassword":fooooooooooo
"ServiceUserName":barrrrrrrrr

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

Use awk :使用awk

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

使用tac (与cat相对)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM