簡體   English   中英

如何反轉grep命令的輸出?

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

我對 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

什么都沒有......也許存在更好的解決方案?

grep 只是過濾器, man grep : print lines matching a pattern ,必須使用另一個工具來改變順序,因為只有兩個項目可能添加|sort|sort -r (反向排序)可以提供幫助。

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

您可以使用和調整以下tac 命令

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

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

使用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