shell Scripts Instances

Extract substring from string

I want to extract MM-ABC-19-97-12-12 from

    559268    clusterA      jobB             usersmith  R       0:12    1 20-00:00:00  gpu:1 MM-ABC-19-97-12-12

solution (surpose the string is stored in file output.txt):

cat output.txt | grep -P 'MM-ABC-19-97-12-12' -o

here -P means Perl-style, and -o means match only.

If we want to match arbitary number after 'MM-ABC', use below patern

cat output.txt | grep -P 'MM-ABC-\d{2}-\d{2}-\d{2}-\d{2}' -o

here \d match a digit and {2} match \d for two times. Further, you can use {2,3} to match \d for two or three times. Here three has a high priority.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.