I'm in bash and I have a file, I want to find all matches of a regex in it and have them printed. How do I do that?

Followup: Assume I want to print only unique matches, i.e. if a match appears multiple times, it should be printed only once. How do I do that? (I want this answer in addition to the first, so I want an answer to the first question too.)

1 Answer 1


Try grep -o 'myregex.*stuff' file and for the second question grep -o 'myregex.*stuff' file | sort | uniq.

The -o grep switch will print only the matches instead of printing the whole line that matches the regex.

  • just a side note, you can use sort -u instead piping to uniq
    – Rabin
    May 13, 2015 at 6:52
  • uniq isn't right, it only handles successive repetitions. Fixed answer. Thank you!
    – Ram Rachum
    May 13, 2015 at 9:42
  • I tend to use sort | uniq in combination instead of sort -u because I might want to extend it to sort | uniq -c | sort -n. Also uniq will be right if you have the output sorted before, like suggested.
    – exic
    May 13, 2015 at 11:56

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.