Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk to print a single next word followin a pattern match

Tags:

awk

This Q is a variation on the theme of printing something after a pattern.

There will be input lines with words. Some lines will match a pattern where the pattern will be one or multiple words separated by space. The pattern might have a leading/trailing space which needs to be obeyed. I need to print the word immediately following the match.

Example input

The quick brown fox jumps over the lazy dog

Pattern : "brown fox "
Desired output : jumps

The pattern will only occur once in the line. There will always be a word following the pattern. There will be lines without the pattern.

awk or sed would be nice.

Cheers.

EDIT :

I failed to ask the question properly. There will be one or more spaces between the pattern and the next word. This breaks Andre's proposal.

    % echo -e "The quick brown fox jumps over the lazy dog\n" | awk -F 'brown fox ' 'NF>1{ sub(/ .*/,"",$NF); print $NF }'
jumps
    % echo -e "The quick brown fox    jumps over the lazy dog\n" | awk -F 'brown fox ' 'NF>1{ sub(/ .*/,"",$NF); print $NF }'
like image 895
Gert Gottschalk Avatar asked Dec 02 '25 06:12

Gert Gottschalk


2 Answers

Disclaimer: this solution assumes that if no pattern is found (There will be lines without the pattern.) it is appropriate to print empty line, if this does not hold true ignore this answer entirely.

I would use AWK for this following way, let file.txt content be

The quick brown fox jumps over the lazy dog
No animals in this line
The quick brown fox   jumps over the lazy dog

then

awk 'BEGIN{FS="brown fox  *"}{sub(/ .*/,"",$2);print $2}' file.txt

output

jumps

jumps

Explanation: I set field seperator FS to "brown fox " followed by any numbers of spaces. What is after this will appear in 2nd column, I jettison from 2nd column anything which is after first space including said space, then print that column. In case there is no match, second column is empty and these actions result in empty line.

like image 123
Daweo Avatar answered Dec 05 '25 14:12

Daweo


This works, given that the desired word is followed by a space:

$ echo -e "The quick brown fox jumps over the lazy dog\n" > file

$ awk -F 'brown fox ' 'NF>1{ sub(/ .*/,"",$NF); print $NF }' file
jumps

Edit: If there're more spaces use this:

$ awk -F 'brown fox' 'NF>1{ sub(/^ */,"",$NF);
                            sub(/ .*/,"",$NF); print $NF }' file
like image 40
Andre Wildberg Avatar answered Dec 05 '25 15:12

Andre Wildberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!