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]
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop










{ 9 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
I have a line abc=xyz
i want to find a pattern “abc=” and if exist print xyz
can some one please help
awk -F “=” ‘{if ($1 like “abc”) print $2 }’
Hi, nice topic.
By the way,
1) using [-F] parameter is totally useless here, there is no point in defining [Field separator] as “:”.
2) As Nikhil stated, test on [$0] is also useless.
3) You may want to get rid of heading 8 space characters, using [substr]
So this code will do the trick:
whois bbc.co.uk | awk ‘/Registrar:/ { getline; print substr($0,9)}’
Thanks to change your article accordingly,
– Philippe