How to get this OUTPUT? perl/awk/sed? How?

Bryn M. Reeves bmr at redhat.com
Wed Jun 22 10:45:14 UTC 2011


On 06/22/2011 07:27 AM, lancebaynes87 wrote:
> How can I generate from this INPUT in "general"
> 
> INPUT (/proc/net/ip_conntrack)
[...]
> OUTPUT
> 
> udp 192.168.1.128 3
> tcp 192.168.1.129 2
> udp 192.168.1.1 1
> tcp 192.168.1.201 1

Mike's perl version is probably more extensible, more readable, more efficent
and more rational but I have a soft spot for awk, sed and pipelines:

$ awk '/^udp/{print $1" "$4} /^tcp/{print $1" "$5}' /tmp/data | sed 's/src=//' |
sort | uniq -c | awk '{print $2" "$3" "$1}' | sort -rk3
udp 192.168.1.128 3
tcp 192.168.1.129 2
udp 192.168.1.1 1
tcp 192.168.1.201 1

The first awk selects the fields and gets them into two identical columns
(prot/src), sed trims of the src= prefix, the first sort gets identical lines to
be adjacent so that the subsequent uniq -c will count them and then the second
awk and final sort get the presentation (column order and reverse sort by count)
into the form specified.

You could also do the whole thing in awk (and probably sed too) but that would
require stopping to think about the problem - this took a minutes or two of "do
this then that.. then, there that looks right.." which is why I still have a
fondness for these tools and the shell's ability to combine them.

Cheers,
Bryn.


More information about the users mailing list