Thursday, May 3, 2012

Awk Print Line After A Matching /regex/

How do I a print line after matching /regex/ using awk under Linux / UNIX operating systems? I'd like print the line immediately after a line that matches /regex/ but not the line that matches itself.

You can use awk, sed and any other tool for the same. Here is awk syntax:
awk '/regex/ { getline; print $0 }' /path/to/file
awk -F: '/regex/ { getline; print $0 }' /path/to/file

getline used to set $0 from next input record; it also set NF, NR, FNR. For example, match 'Registrar:' string and print actual registrar name from whois look up:
whois bbc.co.uk | awk -F: '/Registrar:/ && $0 != "" { getline; print $0}'
Sample output:
        British Broadcasting Corporation [Tag = BBC]

No comments:

Post a Comment