Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print all matches of a regular expression from the command line?

Tags:

regex

grep

perl

What's the simplest way to print all matches (either one line per match or one line per line of input) to a regular expression on a unix command line? Note that there may be 0 or more than 1 match per line of input.

I assume there must be some way to do this with sed, awk, grep, and/or perl, and I'm hoping for a simple command line solution so it will show up in my bash history when needed in the future.

EDIT: To clarify, I do not want to print all matching lines, only the matches to the regular expression. For example, a line might have 1000 characters, but there are only two 10-character matches to the regular expression. I'm only interested in those two 10-character matches.

like image 739
jonderry Avatar asked Nov 28 '22 10:11

jonderry


2 Answers

Assuming you only use non-capturing parentheses,

perl -wnE'say /yourregex/g'

or

perl -wnE'say for /yourregex/g'

Sample use:

$ echo -ne 'fod,food,fad\nbar\nfooooood\n' | perl -wnE'say for /fo*d/g'
fod
food
fooooood
$ echo -ne 'fod,food,fad\nbar\nfooooood\n' | perl -wnE'say /fo*d/g'
fodfood

fooooood
like image 61
ysth Avatar answered Dec 04 '22 03:12

ysth


Unless I misunderstand your question, the following will do the trick

grep -o 'fo.*d' input.txt

For more details see:

  • GNU grep (most platforms)
  • Solaris grep
  • AIX grep
  • HP-UX grep
like image 45
Tom Howard Avatar answered Dec 04 '22 04:12

Tom Howard