The awk
Language
Free stuff! Get the AWK Book!
The awk
language is actually a UNIX filter.
An awk
program consistss of lines that look
like this.
pattern { action}
The awk program runs on each line. If a pattern matches its action is carried out.
There are two special patterns BEGIN
, which matches
before any lines are processed, and END
which matches
after all lines are procesed.
Run these. Why is the second one "stuck?"
awk BEGIN {print "foo"} awk END {print "goo"}
Built-in and User-Defined Variables
Here are the most commonly-used ones. The first four have default values.
FS
field separator, default is a spaceOFS
output field separator, default is a space`RS
row separator, default is \nORS
output row separator, default is \nFILENAME
name of file we ar awking.NF
number of fieldsNR
line number (record number)
Variables just "spring into existence." They have an initial value of 0 or "" and learn their type when first assigned. No variable declarations are needed.
Arithmetic Awk has arithmetic operations: +, -, *, /, and %. The ^ operator exponentiates.
Patterns
Relations among the fields such as $1 == $2, $1 == 45, $3 > 20 /regexes/
Puzzler Print out every other line of a file.
Treasure Hunt What is ~
? What is !~
Boolean Operations Are you suprised to know that
||,
&&
, and !
have their expected meanings?
Functions, User-Defined and Builtin
Math
atan2(y, x)
cos(x)
sin(x)
exp(x)
log(x)
int(x)
sqrt(x)
rand(x)
srand(x)
This has a default value
String
length(str)
tolower(str)
lowercasestoupper(str)
uppercasessubstr(str, start, len)
strtonum(str)
converts a numerical string to a numberprintf(format_string, expression_list)