Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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
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

Your Answer


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.