简体   繁体   中英

How to reverse the output of the grep command?

i have one problem with grep command. 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 ? 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:

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

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

Use awk :

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

使用tac (与cat相对)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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