Awk Print Line After A Matching /regex/

by Vivek Gite on May 13, 2009 · 8 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:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

{ 8 comments… read them below or add one }

1 Hai Vu May 13, 2009

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

Reply

2 Nikhil May 14, 2009

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

Reply

3 GByte May 14, 2009

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

Reply

4 Julio A. Cartaya May 16, 2009

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

Reply

5 nyxx May 16, 2009

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]

Reply

6 Ajay June 8, 2009

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

Reply

7 paddu July 1, 2011

I have a line abc=xyz
i want to find a pattern “abc=” and if exist print xyz
can some one please help

Reply

8 royi January 7, 2012

awk -F “=” ‘{if ($1 like “abc”) print $2 }’

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 3 + 5 ?
Please leave these two fields as-is:
Solve the simple math so we know that you are a human and not a bot.




Previous post:

Next post: