Ari
Ari

Reputation: 4191

Printing All Regex Matches

I'm using the perl/sed commands below to capture and print regex matches, unfortunately, both only print the first match in a line, rather than all matches. How can I modify either or both commands to print all matches? Grep and Awk alternative commands are welcome.

perl -nle 'print "$1" if /.*([0|1]\.[0-9]{0,2}).*/'

sed -rne "s/.*([0|1]\.[0-9]{0,2})/\1/p"

Upvotes: 1

Views: 1140

Answers (2)

Miller
Miller

Reputation: 35208

Just use while with the /g modifier to the regex instead of an if. Also need to get rid of your needless use of .* around the regex.

perl -nle 'print $1 while /([0|1]\.[0-9]{0,2})/g'

Finally, [0|1] should probably just be reduced to [01], unless you want to match a | before the period.

Upvotes: 5

mpapec
mpapec

Reputation: 50667

perl -nle 'print for /([0|1]\.[0-9]{0,2})/g'

Upvotes: 2

Related Questions