I simply need to get the match from a regular expression:

$ cat myfile.txt | SOMETHING_HERE "/(\w).+/"

The output has to be only what was matched, inside the parenthesis.

Don't think I can use grep because it matches the whole line.

Please let me know how to do this.

link|improve this question

80% accept rate
feedback

3 Answers

Use the -o option in grep.

Eg:

$ echo "foobarbaz" | grep -o 'b[aeiou]r'
bar
link|improve this answer
Good grief... Do you have any idea how many times I wrestled with sed backreferences to do that? – Insyte Aug 6 '09 at 17:36
1  
The o option to grep/egrep returns only what matched the entire regular expression, not just what is in () like he asked for. – Kyle Brandt Aug 6 '09 at 17:59
1  
However, that is a very good thing to know anyways :-) – Kyle Brandt Aug 6 '09 at 18:00
feedback

If you want only what is in the parenthesis, you need something that supports capturing sub matches (Named or Numbered Capturing Groups). I don't think grep or egrep can do this, perl and sed can. For example, with perl:

If a file called foo has a line in that is as follows:

/adsdds      /

And you do:

perl -nle 'print $1 if /\/(\w).+\//' foo

The letter a is returned. That might be not what you want though. If you tell us what you are trying to match, you might get better help. $1 is whatever was captured in the first set of parenthesis. $2 would be the second set etc.

link|improve this answer
I was just trying to match what is in parenthesis. Seems like passing it to a perl or a php script might be the answer. – Alex Aug 6 '09 at 18:01
feedback

This will accomplish what you are requesting, but I don't think it is what you really want. I put the .* in the front of the regex to eat up anything before the match, but that is a greedy operation, so this only matches the penultimate \w character in the string.

Note that you need to escape the parens and the +.

sed 's/.*\(\w\).\+/\1/' myfile.txt
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.