AWK Print line number


Ever wanted to display a line number, with each matching record from awk. Useful as a way of counting the number of matching lines too.


Here’s how with a demo which grabs network stats (netstat) off my linux box. It looks for connections to port 80 and in TIME_WAIT state – prints a line number and the matching line.


[[email protected] marcus]$ netstat -an -t | awk ' /:80 / && /TIME_WAIT/ { print ++i,$0} '
0 tcp 0 0 x.x.x.x:80 x.x.x.x:44154 TIME_WAIT

If you wanted the line number, that matches your pattern – this would show that too:

[[email protected] marcus]$ netstat -an -t | awk ' /:80 / && /TIME_WAIT/ { print "line:"NR,"count:"++i,$0} '
line:17 count:1 tcp 0 0 x.x.x.x:4298 x.x.x.x:80 TIME_WAIT


[tags]gawk, netstat, print line numbers, Unix Coding School[/tags]

Comment (1)

  1. Manish

    Exactly what I was looking for…

    …thanks a ton! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *