-4

I want to extract the next word/number after specific words I find using grep or whatnot.

As an example lets say this is what I have in stdout

string-a0 match-a1 string-a2 string-a3
string-b0 string-b1 match-b2 string-b3
match-c0 string-c1 string-c2 string-c3

I want to be left with just this

string-a2
string-b3
string-c1

mind that match-a1 != match-b2 != match-c0

EDIT

A concrete example...

stdout is this

open 0.23 date ...
close 1.52 date ...
open 2.34 date ...
close 5.92 date ...
open 10.78 date ...
close 24.21 date ...
total 45.3

I'm searching for the words open, close and total so the output should be

0.23
1.52
2.34
5.92
10.78
24.21
45.3
Yoni Levy
  • 1,562
  • 2
  • 16
  • 35

2 Answers2

2

This doesn't match the general case, but works for your example:

awk '/^open|^close|^total/{print $2}' input

For the general case, if your definition of "string" is based on whitespace, perhaps you want:

tr -s ' \n' \\n < input | awk 'p{print; p=0} {p=/^open|^close|^total/}'
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • 1
    isn't $2 index specific? I don't necessarily know the location of the next word (index-wise), this is why I put the generic case with `string-*` and `match-*`. Notice how the match position differs – Yoni Levy Jul 13 '16 at 13:52
1

You can use this awk for printing next word after the search word:

awk -v s='^(open|close|total)$' '{for (i=1; i<NF; i++) if ($i ~ s) print $(i+1)}' 

0.23
1.52
2.34
5.92
10.78
24.21
45.3
anubhava
  • 761,203
  • 64
  • 569
  • 643