Awk Variables

Defining variable

awk -v var1="Hello" -v var2="Wold" '
    END {print var1, var2}
' </dev/null

#Use shell variables

awk -v varName="$PWD" '
 END {print varName}' </dev/null

GNU awk only

- -
ENVIRON Environment variables
IGNORECASE Ignore case
CONVFMT Conversion format
ERRNO System errors
FIELDWIDTHS Fixed width fields

Environment Variables

- -
ARGC Number or arguments
ARGV Array of arguments
FNR File Number of Records
OFMT Format for numbers (default "%.6g")
RSTART Location in the string
RLENGTH Length of match
SUBSEP Multi-dimensional array separator (default "\034")
ARGIND Argument Index

Examples

Print sum and average

awk -F: '{sum += $3}
     END { print sum, sum/NR }
' /etc/passwd

Printing parameters

awk 'BEGIN {
    for (i = 1; i < ARGC; i++)
        print ARGV[i] }' a b c

Output field separator as a comma

awk 'BEGIN { FS=":";OFS=","}
 {print $1,$2,$3,$4}' /etc/passwd

Position of match

awk 'BEGIN {
    if (match("One Two Three", "Tw"))
        print RSTART }'

Length of match

awk 'BEGIN {
    if (match("One Two Three", "re"))
        print RLENGTH }'

Expressions

- -
$1 == "root" First field equals root
{print $(NF-1)} Second last field
NR!=1{print $0} From 2th record
NR > 3 From 4th record
NR == 1 First record
END{print NR} Total records
BEGIN{print OFMT} Output format
{print NR, $0} Line number
{print NR " " $0} Line number (tab)
{$1 = NR; print} Replace 1th field with line number
$NF > 4 Last field > 4
NR % 2 == 0 Even records
NR==10, NR==20 Records 10 to 20
BEGIN{print ARGC} Total arguments
ORS=NR%5?",":"\n" Concatenate records

Build-in variables

- -
$0 Whole line
$1, $2...$NF First, second… last field
NR Number of Records
NF Number of Fields
OFS Output Field Separator (default " ")
FS input Field Separator (default " ")
ORS Output Record Separator (default "\n")
RS input Record Separator (default "\n")
FILENAME Name of the file
Comments