Revising awk

January 15, 2013

Awk basics :

NR: Keeps a current count of the number of input lines.

• NF: Keeps a count of the number of words in an input line. The last field in the input line can be designated by $NF.

• FILENAME: Contains the name of the current input file.

• FS: Contains the field separator character. The default is “white space”, meaning space and tab characters. FS can be reassigned to another character to change the field separator.

• RS: Stores the current “record separator” character. Since, by default, an input line is the input record, the default record separator character is a “newline”.

• OFS: Stores the “output field separator”, which separates the fields when Awk prints them. The default is a “space” character.

• ORS: Stores the “output record separator”, which separates the output lines when Awk prints them. The default is a “newline” character.

• OFMT: Stores the format for numeric output. The default format is “%.6g”, which will be explained when “printf” is discussed

Awk examples :

  1.  Write a command to find the sum of bytes (size of file) of all files in a
    ls -l | awk ‘BEGIN {sum=0} {sum = sum + $5} END {print sum}’

References :