Awk is the ideal tool for most of your output processing/formatting needs, we can use it to carefully select and reformat data fields from stdin or a file and even do stuff like using conditions for what the value must be in order to print it, in fact awk is a programming language in itself, but don’t worry too much about that.
We are going to see an example of how we can print the first and second field of a comma separated list, to start with we will need to tell awk how it should split the fields, in this case by a comma, the option have to use is “-F field_separator” so “-F ,”
I’m going to use a file from the output of a metasploit module so you can get an idea of how useful this can be.
cat .msf4/logs/scripts/winenum/WINXP-95C9409AB_20110828.5732/wmic_useraccount_list.csv | awk -F , '{ print $4 "t" $10 }'
Disabled Name
FALSE Administrator
TRUE Guest
TRUE HelpAssistant
TRUE
FALSE test
FALSE winxpPro
We use the print statement which executes once per line of input notice how it goes between brackets and single quotes or it won’t work, then we specify the field number using a dollar sign, so for field 4 $4, finally if we want to have our own text or even a tab or newline we need to enclose it between double quotes.
As a second example let’s split /etc/passwd and print the whole line for those users with a uid greater than 1000, for this example we will need to use an if statement and split on colon.
root@bt:~# awk -F : '{ if ($3 >; 1000) print $0 }' /etc/passwd
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
matu:x:1001:1001::/home/matu:/bin/bash
In this example we print the whole line using $0, if $3 (uid) is greater than 1000.
There is a lot more you can do with Awk, one good place to look at is over here.

Leave a Reply