print next word after found pattern

Hi all,

I'd like to print the next word after a found pattern.

example text:

word1 word2 word3 word4 pattern word5

pattern word1 word2 word3 word4

word1 word2 pattern word4

basiclly the word after pattern.

Thanks

What happens when the pattern is last on the line?

it never is

Try this:

awk '{for(i=1;i<=NF;i++)if($i~/pattern/)print $(i+1)}' infile
1 Like

perfect thanks

i have a similar situation and i thought i'd drop my question here...

i have a file like below. how to printout the digits followed by the pattern -bwout and -bwin. say i run the script by entering line number 145 (the fourth line), then the o/p should be like
5000000 1024000

8 test1 -ipprot erp -ppsout 500 -ppsin 500 -bwout 300000 -bwin 300000 -statsdevice test1 -stats 
30 test2 -addr a.b.c.249 -wdwthresh 3 -bwout 512000 -bwin 512000 -statsdevice test2 -stats 
125 test3 -addr a.b.c.0 -addrmsk 255.255.255.0 -bwlink total1 -statsdevice testing3 -stats -global 
145 test4 -group -bwout 1024000 -bwin 5000000 -statsdevice group4 -stats 
1451 test5 -addr a.b.c.251 -bwout 256000 -bwin 512000 -bwlink test4 -statsdevice test5 -stats 
14539 test6 -addr a.b.c.34 -bwboth 128000 -bwlink xyz128 -statsdevice abc123 -stats

did i make myself clear?

tia

Please do not Bump posts as it's not allowed in the forum. Request you to open a new thread.Thanks!

awk -v var=145 '$1==var {for(i=1;i<=NF;i++) {if($i=="-bwout") print $(i+3),$(i+1)}}' file
5000000 1024000
echo "Enter the line number";read num; awk -v line=$num '{if($1==line){for(i=1;i<=NF;i++){if($i ~ /-bwout/)x=$(i+1);if($i ~ /-bwin/)y=$(i+1);}}} END{print y" "x;}' file

file will have the contents you pasted.

1 Like

thank you all