linuxbashshellgrep

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?


Solution

  • 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 -E '"ServiceUserName"|"ServicePassword"' | sort -r >> user.txt
    

    UPDATED after @therobyouknow comment, sort -r work only for this specific case because lexicographically "Password" is before "UserName" to reverse the output in the general case tac can be used instead.