AWK

AWK “simple form”:

      awk search pattern { program actions }

AWK “general form”:

BEGIN { initializations }  search pattern 1 { program actions } search pattern 2 { program actions } ... END { final actions }

ls -l | awk 'BEGIN{print "Owner\tFile"} {print $3, "\t", $9} END{print "Job done for " NR " lines"}'

AWK Built-in Variables

FS - The Input Field Separator Variable (‘-F’ as commandline parameter - by default, -F ‘ ‘) OFS - The Output Field Separator Variable NF - The Number of Fields Variable NR - The Number of Records Variable RS - The Record Separator Variable ORS - The Output Record Separator Variable FILENAME - The Current Filename Variable

AWK commands

There are only a few commands in AWK. The list and syntax follows:

if ( conditional ) statement [ else statement ]
while ( conditional ) statement
for ( expression ; conditional ; expression ) statement
for ( variable in array ) statement
break
continue
{ [ statement ] ...}
variable=expression
print [ expression-list ] [ > expression ]
printf format [ , expression-list ] [ > expression ]
next
exit

Some printf formats

%5s or %-5s –> Print string in 5 position field (‘-’ aligns text left justified)
%5.2f –> Print number (float) in a 5 position field with 2 decimals
%5.2d –> Print number in a 5 position field with minimum 2 digits to print

Some examples

Taking an access.log file with lines like

163.56.115.58 - - [09/Jan/2017:22:29:57 +0100] "GET /posts/2/display HTTP/1.0" 200 3240

awk '/ 200 / {print $1,$8,$7,$6}' access.log

163.56.115.58 HTTP/1.0" /posts/2/display "GET

awk '/ 200 / {print $1 $8 $7 $6}' access.log

163.56.115.58HTTP/1.0"/posts/2/display"GET

Print line 25 of a file

awk NR==25 <file>

(or sed 25!d <file>    or    sed -n 25p <file>)

(or head -25 faces.txt | tail -1)

Print text in tabulated (table) format

awk -F ',' '{printf("%-5s %-5s %-5s\n", $1, $2, $3)}' table.csv

http://www.grymoire.com/Unix/Awk.html

https://www.linuxnix.com/awk-scripting-learn-awk-built-in-variables-with-examples/