Hein
Hein

Reputation: 175

grep for a value after two words

In a file there is are repeatedly lines like

value for = 0.658
value b = 0.431
value ty = 0.001

The line starts with value. I would like to only grep the number in the value for line (0.658) and there is always the = before it. The problem is that = is also in front of the other lines of the file. I know how to grep for the line of the two words value and for but don't know how to grep the number only?

Upvotes: 1

Views: 364

Answers (4)

devsnd
devsnd

Reputation: 7722

grep "value for" YOURFILE | grep -Po '([\[0-9\]\.]+)'

The first grep makes sure only the necessary lines are passed to the second, which only outputs the matching parts (due to the -o switch).

Upvotes: 0

Stephen Kennedy
Stephen Kennedy

Reputation: 21558

By default, grep will print the entire line if you have a match (see 'man grep').

The -o option will instead output only the part of lines matching the regex. So, to output all numbers on lines with numbers we can do:

grep -Eo '[0-9]+' filename

To restrict to lines with 'value for = ' and a number we can use a Perl regex (-P) and discard the first part of the match by using \K in our expression:

grep -Po 'value for \= \K[0-9]+' filename

Upvotes: 0

JoErNanO
JoErNanO

Reputation: 2488

Use a regexp that matches numbers. Something like:

\d?\.?\d*

Here is a screenshot of regexpal in action: enter image description here

Upvotes: 0

Cyrus
Cyrus

Reputation: 88674

You can try this:

grep -oP 'value for = \K.*' filename

Output:

0.658

See: http://www.charlestonsw.com/perl-regular-expression-k-trick/

Upvotes: 2

Related Questions