Tuesday, May 20, 2008

AWK by example

# count lines (emulates "wc -l")
awk 'END{print NR}'

# print the sums of the fields of every line
awk '{s=0; for (i=1; i<=NF; i++) s=s+$i; print s}'

# add all fields in all lines and print the sum
awk '{for (i=1; i<=NF; i++) s=s+$i}; END{print s}'

# print the total number of fields ("words") in all lines
awk '{ total = total + NF }; END {print total}' file

# print every line where the value of the last field is > 4
awk '$NF > 4'

# substitute "foo" with "bar" ONLY for lines which contain "baz"
awk '/baz/{gsub(/foo/, "bar")};{print}'

# substitute "foo" with "bar" EXCEPT for lines which contain "baz"
awk '!/baz/{gsub(/foo/, "bar")};{print}'

# switch the first 2 fields of every line
awk '{temp = $1; $1 = $2; $2 = temp}' file

# print line number 52
awk 'NR==52'
awk 'NR==52 {print;exit}' # more efficient on large files

# print section of file between two regular expressions (inclusive)
awk '/Iowa/,/Montana/' # case sensitive

# delete ALL blank lines from a file (same as "grep '.' ")
awk NF
awk '/./'