Skip to main content

awk

Ref: The GNU Awk User’s Guide

awk 
{ '<program>' | -f '<program file>' }
[<input file> [...]]

<program>

# A BEGIN rule is executed once only, before the first input record is read.
BEGIN {
# <action>
}

# The BEGINFILE rules is executed just before gawk reads the first record from a file.
BEGINFILE {
# <action>
}

# If the pattern is omitted, then the action is performed for every record.
<pattern> {
# <action>
}

# The ENDFILE rule is called when gawk has finished processing the last record in an input file.
ENDFILE {
# <action>
}

# An END rule is executed once only, after all the input is read.
END {
# <action>
}

Default <action> is print

<pattern> {
print
}

# equal to

<pattern>

Built-in Variable

NameDescriptionDefault
ARGCArgument Count
ARGVArgument Value
$0Current Record
$1, $2, ..., $NFField 1, Field 2, ..., Last Field
NFNumber of Fields
NRNumber of Records has processed
FSField Separator" "
OFSOutput Field Separator" "
IGNORECASEIgnore Case
RSRecord Separator"\n"
ORSOutput Record Separator"\n"

Pattern

Regular expression

/<regular expression>/

Expression

<expression> == <expression>
<expression> != <expression>
<expression> < <expression>
<expression> <= <expression>
<expression> > <expression>
<expression> >= <expression>

# Match Reg Exp
<expression> ~ /<reg exp>/

# Not match Reg Exp
<expression> !~ /<reg exp>/

Range

<begin pattern>,<end pattern>

Emtpy

Match every record

Assignment Expression

<variable> = <value>

String

"<string>"

if

if (<condition>) {
# <code>
# ...
}

if (<condition>) {
# <code>
# ...
} else {
# <code>
# ...
}

RegExp

Match

<value> ~ /<reg exp>/

Not match

<value> !~ /<reg exp>/

Default <string> is $0

/<reg exp>/

# equal to

$0 ~ /<reg exp>/

Print

{
print <item>[, ...]
}

Default <item> is $0

{
print $0

# equal to

print
}