Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a large file, and I'm trying to get all matches of a regular expression from it.

grep -P "foo (b.r)"

Displays all the lines containing «foo b.r», and I'd like to display only what's inside of the brackets.

Pro question: what to do if I have more than one bracket set? For example «foo (b.r) foo (.ar)», and I want the output to consist only of the thing in the first and the second bracket, separated by a separator.

I'm tagging this Perl, because I'm sure I could use «perl -e "..."» - the question to Perl experts, how to write this? It's been ages since I used Perl :)

share|improve this question
add comment

2 Answers

Perhaps use grep's -o

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

which will leave you with the entire pattern, then follow up with another sed(?) to remove/replace the (foo) delimiters?

I doubt it's 'efficient' but it'll do the job.

share|improve this answer
add comment
perl -ne '/foo \((.+?)\)/ and print "$1\n";'

Here \( \) are literal parentheses and ( ) create a group.

If a line can match multiple times, this should work:

perl -ne 'print "$1\n" for /foo \((.+?)\)/g;'

Decrypting oneliners:

  • a and bif (a) {b}
  • b if aif (a) {b}
  • b for afor (a) {b}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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