1

I would like to grep digits inside a set of parentheses after a match.

Given foo.txt below,

foo: "32.1" bar: "42.0" misc: "52.3"

I want to extract the number after bar, 42.0.

The following line will match, but I'd like to extract the digit. I guess I could pipe the output back into grep looking for \d+.\d+, but is there a better way?

grep -o -P 'bar: "\d+.\d+"' foo.txt
EarthIsHome
  • 655
  • 6
  • 18
  • Does this answer your question? [How to grep for contents after pattern?](https://stackoverflow.com/questions/10358547/how-to-grep-for-contents-after-pattern) – tripleee Sep 27 '22 at 04:23

2 Answers2

3

One way is to use look ahead and look-behind assertions:

grep -o -P '(?<=bar: ")\d+.\d+(?=")'

Another is to use sed:

sed -e 's/.*bar: "\([[:digit:]]\+.[[:digit:]]\+\)".*/\1/'
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • Awesome! I didn't know about those. :-) More info on look-ahead and look-behind assertions in Perl can be found here: http://www.perlmonks.org/?node_id=518444 – EarthIsHome Oct 08 '14 at 03:47
1

You could use the below grep also,

$ echo 'foo: "32.1" bar: "42.0" misc: "52.3"' | grep -oP 'bar:\s+"\K[^"]*(?=")'
42.0
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274