Awk Quick Ref
Awk Quick Ref
* This final section provides a convenient lookup reference for Awk programming.
If you want a more detailed reference and are using a UN*X or Linux system, you
might look at the online awk manual pages by invoking:
man awk
Apparently some systems have an "info" command that is the same as "man" and
which is used in the same way.
* Invoking Awk:
awk [-F<ch>] {pgm} | {-f <pgm file>} [<vars>] [-|<data file>]
-- where:
ch: Field-separator character.
pgm: Awk command-line program.
pgm file: File containing an Awk program.
vars: Awk variable initializations.
data file: Input data file.
* Search patterns:
/<string>/ Search for string.
/^<string>/ Search for string at beginning of line.
/<string>$/ Search for string at end of line.
The search can be for an entire range of lines, bounded by two strings:
/<string1>/,/<string2>/
The search can be for any condition, such as line number, and can use the
following comparison operators:
== != < > <= >=
* Special characters:
\n Newline (line feed).
* Built-in variables:
$0; $1,$2,$3,... Field variables.
- 1-
An Awk Primer
* Arithmetic operations:
+ Addition.
- Subtraction.
* Multiplication.
/ Division.
% Mod.
++ Increment.
-- Decrement.
Shorthand assignments:
x += 2 -- is the same as: x = x + 2
x -= 2 -- is the same as: x = x - 2
x *= 2 -- is the same as: x = x * 2
x /= 2 -- is the same as: x = x / 2
x %= 2 -- is the same as: x = x % 2
* Arithmetic functions:
sqrt() Square root.
log() Base \Ie\i log.
exp() Power of \Ie\i.
int() Integer part of argument.
* String functions:
• length()
Length of string.
Get substring.
• split(<string>,<array>,[<field separator>])
• sprintf()
* Control structures:
if (<condition>) <action 1> [else <action 2>]
while (<condition>) <action>
for (<initial action>;<condition>;<end-of-loop action>) <action>
- 2-
An Awk Primer
* Print:
print <i1>, <i2>, ... Print items separated by OFS; end with newline.
print <i1> <i2> ... Print items concatenated; end with newline.
* Printf():
General format:
printf(<string with format codes>,[<parameters>])
* Awk can perform output redirection (using ">" and ">>") and piping (using
"|") from both "print" and "printf".
- 3-