I have same: 1.txt with apple written in it, 2.txt with mango written in it, 3.txt with apple written in it, 4.txt with mango written in it.

grep -e apple -e mango *.txt will give result as:

1.txt: apple
2.txt: mango
3.txt: apple
4.txt: mango

But I need output as:

1.txt: apple
3.txt: apple
2.txt: mango
4.txt: mango

Is it possible with just grep command ? -- without using any other command like sort or so

  • 2
    No, and even if there was, it would be wrong. Use sort. – Chris Down Mar 26 '15 at 13:11
  • No, grep does not perform sorting. – jordanm Mar 26 '15 at 13:11
  • 1
    If you want to use only grep then you've to do grep -e apple *.txt; grep -e mango *.txt manually – Pandya Mar 26 '15 at 13:22

It is not possible by only using grep. You have to use another tool e.g. sort:

$ grep -e apple -e mango *.txt | sort -t: -k2,2
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.