Home > Blockchain >  Apply a regular expression to a string in bash to get all the ocurrences of a group
Apply a regular expression to a string in bash to get all the ocurrences of a group

Time:09-19

I have a shell variable with a string like the following "PA-232 message1 GX-1234 message2 PER-10 message3"

I need to apply a regular expression that detects PA-232, GX-1234 and PER-10 and returns these ocurrences.

How can I do this in bash?

I've tried this:

echo "PA-232 message1 GX-1234 message2 PER-10 message3" | sed -r 's/^.*([A-Z] -[0-9] ).*$/\1/'

But it returns

R-10

instead of

PA-232
GX-1234
PER-10

CodePudding user response:

$ echo "PA-232 message1 GX-1234 message2 PER-10 message3" | grep -Eo '[A-Z] -[0-9] '
PA-232
GX-1234
PER-10

CodePudding user response:

A Perl:

$ echo "PA-232 message1 GX-1234 message2 PER-10 message3" | perl -lnE 'while(/([A-Z] -\d )/g){ say $1 }'

Or awk:

$ echo "PA-232 message1 GX-1234 message2 PER-10 message3" | awk '{for(i=1;i<=NF;i  ) if($i~"^[A-Z][A-Z]*-[[:digit:]][[:digit:]]*$") print $i}'

Either prints:

PA-232
GX-1234
PER-10
  • Related