awk command examples Flashcards
Fields in awk
Inserting a couple of tabs and a string
kelly@octarine ~/test> ls -ldh * | grep -v total | \ awk ‘{ print “Size is “ $5 “ bytes for “ $9 }’
Size is 160 bytes for orig Size is 121 bytes for script.sed
Size is 120 bytes for temp_file
Size is 126 bytes for test
Size is 120 bytes for twolines
Size is 441 bytes for txt2html.sh
take out any number of columns and even reverse the order
kelly@octarine ~> df -h | sort -rnk 5 | head -3 | \ awk ‘{ print “Partition “ $6 “\t: “ $5 “ full!” }’
Partition /var : 86% full!
Partition /usr : 85% full!
Partition /home : 70% full!
displays only local disk device information, networked file systems are not shown
kelly is in ~> df -h | awk ‘/dev\/hd/ { print $6 “\t: “ $5 }’
/ : 46%
/boot : 10%
/opt : 84%
/usr : 97%
/var : 73%
/.vol1 : 8%
search the /etc directory for files ending in “.conf” and starting with either “a” or “x”, using extended regular expressions
In order to precede output with comments, use the BEGIN statement
The END statement can be added for inserting text after the entire input is processed
awk script contains awk statements defining patterns and actions
input field separator
kelly is in ~> awk ‘BEGIN { FS=”:” } { print $1 “\t” $5 }’ /etc/passwd
–output omitted–
kelly Kelly Smith
franky Franky B.
eddy Eddy White
willy William Black
cathy Catherine the Great
sandy Sandy Li Wong
input field separator in awk script
kelly is in ~> cat printnames.awk
BEGIN { FS=”:” } { print $1 “\t” $5 }
kelly is in ~> awk -f printnames.awk /etc/passwd –output omitted–
The output field separator
kelly@octarine ~/test> cat test
record1 data1
record2 data2
kelly@octarine ~/test> awk ‘{ print $1 $2}’ test record1data1
record2data2
kelly@octarine ~/test> awk ‘{ print $1, $2}’ test
record1 data1
record2 data2
output record separator
kelly@octarine ~/test> awk ‘BEGIN { OFS=”;” ; ORS=”\n–>\n” } \ { print $1,$2}’ test
record1;data1
–>
record2;data2
–>
count the total number of records
kelly@octarine ~/test> cat processed.awk
BEGIN { OFS=”-“ ; ORS=”\n–> done\n” } { print “Record number “ NR “:\t” $1,$2 } END { print “Number of records processed: “ NR }
kelly@octarine ~/test> awk -f processed.awk test Record number 1: record1-data1
–> done
Record number 2: record2-data2
–> done
Number of records processed: 2
–> done