I've lots of files which lines looks like

lotsofblah/XY##_####_morefoo

where # is a number. Now i want to show only the parts

YZ##_####

in the bash, each in a new line of course.

link|improve this question
feedback

2 Answers

up vote 2 down vote accepted

Assuming you want XY to be any two letters...

Something like

grep -Eo "[A-Z]{2}[0-9]{2}_[0-9]{4}" file

Would match [two letters][two numbers]_[four numbers]

If you wanted, it could be a little more exact, making sure there's a / infront and a _ afterwards, but this is a starting point.

Put this together from man grep:

-E, --extended-regexp
          Interpret PATTERN as an extended regular expression (see below)

-o, --only-matching
          Show only the part of a matching line that matches PATTERN.

and http://www.regular-expressions.info/reference.html

link|improve this answer
feedback

I suppose that XY and YZ are the same, and I'll treat them just as XY

egrep "XY[0-9]{2}_[0-9]{4}" filename -o

The key is the -o option that shows only the matching text.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.