Krish Krish - 1 month ago 6
Perl Question

Get the word after a match in a line when line has multiple match

I have a big text file with content as below:

Register foo1 ... Register foo2 ... Register foo10...
Register foo20 ...
Un-Register bar1 ... Register foo21 ...


I wrote below bash script, which will work only if there is one "Register" per line, but how to get all foo's in same line?

#!/bin/bash
file=/tmp/log
grep -e 'Register\s' $file | awk '{print $2}' | grep -v Un-Register | while read -r line; do
#do something with $line
done

Answer

Try this :

perl -pe 's/\s+Register/\nRegister/g' file |
  grep -oP '^Register\s+\Kfoo\S*'

Output :

foo1
foo2
foo10...
foo20
foo21
Comments