Thursday, July 14, 2016

Basic AWK examples

AWK basic format
$ awk 'BEGIN { initializations } search pattern 1 { program actions } search pattern 2 { program actions }  ...  END { final actions }' input file


Example show first and second column
$ ls -l  |   awk ' { print $1,$2 } '

Example showing only the lines that contains a pattern
$ ls -l | awk ' /teste/ { print $1,$2 } '

Example showing only the lines that contains the pattern in the nth column
This filters the line that contains the string teste in the 9th column
$ ls -l | awk '$9  ~ /teste/ { print $8,$NF }'
This filters the line that is the 9th column is equal to teste
$ ls -l | awk '$9  == "teste" { print $8,$NF }' 

Example printing the current line number

$ ls -l | awk ' {  print NR } '

Example printing formating output

$ ls -l | awk '{ printf "%d %s\n", NR, $0 }'

Example setting the separator character

$ echo "teste|uol|bla" | awk 'BEGIN { RS="|" } { printf "%s\n", $0 } '

$ echo -e "record 0 record xxx record 1 AAAA record 2 BBBB record 3 yyy" | awk 'BEGIN { RS = "\n|( *[[:upper:]]+ *)" }  { print "Record =", $0, "and RT =", RT }'

Example running external command and print result
$ ls | awk '{ while ((("find /dev" | getline g)) > 0) { print g;} }'


$ ps ef -o pid= | \
 awk ' BEGIN {
                x=0;
        }
        {
        cmd = "sudo ls -l /proc/" $1 "/exe "
         while ( ( cmd | getline res ) > 0 )
        {
                 printf "%d -  %s\n", x, res
                 x++;
        }
        close(cmd)
}'

More complete example

Suppose you have two files with name teste

$ ls -1

Now you want to list and count how many files has the string teste in its name.

$ ls -1 | awk 'BEGIN { x=0; } /teste/ { print x++, $1; } END { print "TOTAL", x }'




No comments:

Blog Archive