Monday, January 20, 2014

Unix / Linux Power Tools - awk for group by

You have a list of commands issued let us say from a log trace. You want to provide a report that shows at least one example per command which demands showing not just the command but also the parameters being passed. For example:
$ cat /tmp/test command1 param1 param2 command2 param3 param4 command1 param5 para6
$ cat /tmp/test | awk '{ array[$1]=$0; }  END {for (i in array) print array[i]}'
command2 param3 param4
command1 param5 para6
We use $1 (the command) as the key and the whole line ($0) as a value in an associative array which guarantees a unique entry per command (in our case the last entry). At the END we print the array content.

No comments: