Revising awk

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
    directory.
    ls -l | awk ‘BEGIN {sum=0} {sum = sum + $5} END {print sum}’

References :

  1. http://oreilly.com/catalog/unixnut3/chapter/ch11.html
  2. http://www.chemie.fu-berlin.de/chemnet/use/info/gawk/gawk_17.html

http://www.catonmat.net/blog/awk-one-liners-explained-part-one/

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: