awk built-in variables and functions reference
Complete reference for awk built-in variables (NR, NF, FS), string functions, and arithmetic functions.
awk built-in variables and functions reference
Complete reference for awk built-in variables (NR, NF, FS), string functions, and arithmetic functions.
awk Built-In Variables
| Variable | Description | Example |
|---|---|---|
$0 | The entire current input line. | {print $0} prints the whole line |
$1,
$2, ...
$NF | Individual fields, split by
FS. | {print $1, $3} |
NR | Total number of records (lines) read so far across all files. | END {print NR} prints total line count |
NF | Number of fields in the current record. | {print NF} prints field count per line |
FS | Input field separator. Default: whitespace. Set with
-F or in
BEGIN. | BEGIN {FS=":"} |
OFS | Output field separator. Default: space. | BEGIN {OFS="\t"} |
RS | Input record separator. Default: newline. | BEGIN {RS="\n\n"} for paragraph mode |
ORS | Output record separator. Default: newline. | BEGIN {ORS="; "} |
FILENAME | Name of the current input file. | {print FILENAME, $0} |
FNR | Record number within the current file (resets per file). | FNR == 1 matches each file's first line |
awk String Functions
| Function | Description | Example |
|---|---|---|
length(s) | Returns the length of string
s. | {print length($1)} |
substr(s, start, len) | Returns a substring of
s starting at position
start. | {print substr($0, 1, 10)} |
index(s, target) | Returns position of
target in
s, or 0 if not found. | index($0, "error") |
split(s, arr, sep) | Splits
s into array
arr by separator
sep. Returns element count. | split($3, parts, ":") |
sub(regex, repl, s) | Replaces the first match of
regex in
s with
repl. | sub(/old/, "new", $0) |
gsub(regex, repl, s) | Replaces all matches of
regex in
s with
repl. Returns count. | gsub(/,/, "\t", $0) |
tolower(s) | Converts
s to lowercase. | {print tolower($1)} |
toupper(s) | Converts
s to uppercase. | {print toupper($1)} |
sprintf(fmt, ...) | Returns a formatted string (like C printf). | sprintf("%.2f", $3) |
awk Arithmetic Functions
| Function | Description | Example |
|---|---|---|
int(x) | Truncates
x to integer. | int(3.9) returns
3 |
sqrt(x) | Returns the square root of
x. | sqrt(144) returns
12 |
log(x) | Returns the natural logarithm of
x. | log(2.718) returns
~1 |
exp(x) | Returns e raised to the power
x. | exp(1) returns
~2.718 |
sin(x),
cos(x) | Trigonometric functions (radians). | sin(3.14159/2) returns
~1 |
rand() | Returns a random number between 0 and 1. | {print rand()} |
srand(seed) | Sets the random seed. | BEGIN {srand()} |