Awk Print Line After A Matching /regex/

by Vivek Gite · 6 comments

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]

Featured Articles:

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 6 comments… read them below or add one }

1 Hai Vu 05.13.09 at 4:03 pm

I suggest to use print instead of print $0: it is shorter.

2 Nikhil 05.14.09 at 9:06 am

$0 != “” looks like a redundant check since it is still the line matching the regex and not the next line.

3 GByte 05.14.09 at 9:15 am

How about:
$pgrep -A 1 regexp | tail -n 1
?

4 Julio A. Cartaya 05.16.09 at 10:17 am

Simply saying:
$ awk ‘/regexp/’ /pathto/file
will do the trick: the default action in awk is printing.

5 nyxx 05.16.09 at 6:26 pm

Reducing awk code for a while we’ll get tha same
$ whois bbc.co.uk | awk -F: '/Registrar:/ { getline; print }'
British Broadcasting Corporation [Tag = BBC]

6 Ajay 06.08.09 at 3:12 am

You can us grep as well:
whois bbc.co.uk | grep -A 1 Registrar| grep -v Registrar

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous FAQ:

Next FAQ:

nixCraft FAQ PDF Collection Now Available To All