bash 如何反转grep命令的输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44842635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reverse the output of the grep command?
提问by Андрей Ка
i have one problem with grep command. in my called script i use:
我对 grep 命令有一个问题。在我调用的脚本中,我使用:
"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 ? I need it only this sequence. i try to change:
但是在 user.txt 文件中,我将首先获得“ServicePassword”:fooooooooooo 然后是“ServiceUserName”:barrrrrrrrr 我如何使用 grep 命令反转它以在 user.txt 文件中获得第一个 ServiceUserName 然后 ServicePassword 输出?我只需要这个序列。我尝试改变:
grep -E '""ServicePassword""|"ServiceUserName"' >> user.txt
and nothing.... maybe exist a better solution?
什么都没有......也许存在更好的解决方案?
回答by Nahuel Fouilleul
grep just filters, man grep
: print lines matching a pattern
, to change order another tool must be used, as there's only two items maybe adding |sort
or |sort -r
(sort reverse) can help.
grep 只是过滤器,man grep
: print lines matching a pattern
,必须使用另一个工具来更改顺序,因为只有两个项目可能添加|sort
或|sort -r
(反向排序)可以提供帮助。
grep -E '"ServiceUserName"|"ServicePassword"' | sort -r >> user.txt
回答by Elio Messina
You can use and adapt the tac commandbelow:
您可以使用和调整以下tac 命令:
$ cat test.txt
"ServicePassword":fooooooooooo
"ServiceUserName":barrrrrrrrr
$ egrep '"ServicePassword"|"ServiceUserName"' test.txt | tac
"ServiceUserName":barrrrrrrrr
"ServicePassword":fooooooooooo
回答by hek2mgl
Use awk
:
使用awk
:
awk '/ServicePassword/{pwd=##代码##};/ServiceUserName/{user=##代码##};
END{printf pwd; print user}'