Awk reference

From thelinuxwiki
Jump to: navigation, search

Contents

special varialbles

NR is the number of records or lines
NF is the number of fields in a line

printing from the END of a line

printing the last word, next to last word, and 2nd from last word from a line respectively...

awk '{ print $NF }'
awk '{ i = NF-1; print $i }'
awk '{ i = NF-2; print $i }'


loop through fields from begging to end of line

awk -F ";" '{for (i=1; i<=NF; i++) print $i}'

read a particular line / record from file

awk "NR==$i" $FILENAME

example of above in variable assignment

FOO=$(awk "NR==$i" $FILENAME)


print all but a particular field or fields

set field you want to exclude to null

awk '{$1=""; print }'

color formatted output

To get color output from awk, you can use this approach.

function red(s) {
   printf "\033[1;31m" s "\033[0m "
}
function green(s) {
   printf "\033[1;32m" s "\033[0m "
}
function blue(s) {
   printf "\033[1;34m" s "\033[0m "
}
{
    print red($1), green($2), blue($3)
}

example one liner

echo "red text is cool" | awk 'function red(s) {printf "\033[1;31m" s "\033[0m "} {print red($1) $2, $3, $4 }'