[problem]
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.
[/problem]
[solution]
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.
[/solution]
[example]
[marcus@bree 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:
[marcus@bree 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
[/example]
[reference]
[tags]gawk, netstat, print line numbers, Unix Coding School[/tags]
[/reference]
If you have found my website useful, please consider buying me a coffee below 😉