2

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

2 Answers 2

3

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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .