Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading