kota's memex

program structure

AWK scans a sequence of input lines one after another, searching for lines that are matched by and of the patters in the program. For each pattern that matches, the corresponding action is performed. Then the next line is read and the matching starts over:
pattern { action }

running awk programs

awk 'program' input files

variables

NF = the number of fields in the line
NR = the line number (starting at 1)
FILENAME = the filename being processed

This prints the first column of a file and the filename and sorts by the first columns (as numbers):
find . -mindepth 1 -exec awk '{ printf ("%s %s\n", $1, FILENAME) }' '{}' \;|sort -n -r

printf

You may use printf to format the output exactly as you'd like. This can be used to line up fields for example:
{ printf ("%-8s %6.2f\n", $1, $2) }

The first specification %-8s prints a string of characters left justified in a field 8 characters wide. The second specification %6.2f prints a number with two digits after the decimal place, in a field 6 characters wide (padded with spaces to the right)

useful one-liners

Print the first two fields, in opposite order, of every line:
{ print $2, $1 }

Exchange the first two fields then print the full line:
{ temp = $1; $1 = $2; $2 = temp; print }

Print the total number of input lines:
END { print NR }

Print the tenth input line:
NR == 10

Print the last field of every input line:
{ print $NF }

Print the last input line:\

{ field = $NF }
END { print field }

Print every input line with more than four fields:
NF > 4

Print every input line in which the last field is more than 4:
$NF > 4

Print the total number of fields in all input lines:\

{ nf = nf + NF }
END { print nf }

Print the total number of lines that contain Kota:\

/Kota/ { nlines = nlines + 1 }
END { print nlines }

Print the largest first field and the line that contains it (assumes $1 is possitive):\

$1 > max { max = $1; maxline = $0 }
END { print max, maxline }

Print every line that has at least one field:
NF > 0

Print every line longer than 80 characters:
length($0) > 80

Print the number of fields in every line followed by the line itself:
{ print NF, $0 }

Print every line with the first field replaced with the line number:
{ $1 = NR; print }

Print every line after erasing the second field:
{ $2 = ""; print }

Print in reverse order the fields of every line:\

{ for (i = NF; i > 0; i = i - 1) printf("%s ", $i)
 printf("\n")
}

Print the sums of the fields of every line:\

{ sum = 0
 for (i = 1; i <= NF; i = i + 1) sum = sum + $i
 print sum
}

Add up the fields in all lines and print the sum:\

{ for (i = 1; i <= NF; i = i + 1) sum = sum + $i
END { print sum }

Print every line after replacing each field by it's absolute value:\

{ for (i = 1; i <= NF; i = i + 1) if ($1 < 0) $i = -$i
 print
}

Skip blank lines (0 fields) and lines that start with #:
awk 'NF { if( $1 != "#" ){ print $0 } }'