Bash – Seeing all regex matches in a file in Bash

bashfilesregular expression

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.)

Best Answer

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.

Related Question