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:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- My 10 UNIX Command Line Mistakes
- 10 Greatest Open Source Software Of 2009
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
- Email FAQ to a friend
- Download PDF version
- Printable version
- Comment RSS feed
- Last Updated: 05/13/09



{ 6 comments… read them below or add one }
I suggest to use print instead of print $0: it is shorter.
$0 != “” looks like a redundant check since it is still the line matching the regex and not the next line.
How about:
$pgrep -A 1 regexp | tail -n 1
?
Simply saying:
$ awk ‘/regexp/’ /pathto/file
will do the trick: the default action in awk is printing.
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]
You can us grep as well:
whois bbc.co.uk | grep -A 1 Registrar| grep -v Registrar