Console9

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

VariableDescriptionExample
$0The entire current input line.{print $0} prints the whole line
$1, $2, ... $NFIndividual fields, split by FS.{print $1, $3}
NRTotal number of records (lines) read so far across all files.END {print NR} prints total line count
NFNumber of fields in the current record.{print NF} prints field count per line
FSInput field separator. Default: whitespace. Set with -F or in BEGIN.BEGIN {FS=":"}
OFSOutput field separator. Default: space.BEGIN {OFS="\t"}
RSInput record separator. Default: newline.BEGIN {RS="\n\n"} for paragraph mode
ORSOutput record separator. Default: newline.BEGIN {ORS="; "}
FILENAMEName of the current input file.{print FILENAME, $0}
FNRRecord number within the current file (resets per file).FNR == 1 matches each file's first line

awk String Functions

FunctionDescriptionExample
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

FunctionDescriptionExample
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()}