This is a one page quick reference cheat sheet to the GNU awk, which covers commonly used awk expressions and.
$ awk -F: '{print $1, $NF}' /etc/passwd
β -F: β Colon as a separator
β {...} β Awk program
β print β Prints the current record
β $1 β First field
β $NF β Last field
β /etc/passwd β Input data file
BEGIN {<initializations>}
<pattern 1> {<program actions>}
<pattern 2> {<program actions>}
...
END {< final actions >}
awk '
BEGIN { print "\n>>>Start" }
!/(login|shutdown)/ { print NR, $0 }
END { print "<<<END\n" }
' /etc/passwd
$1 $2/$(NF-1) $3/$NF
βΌ βΌ βΌ
ββββββββ¬βββββββββββββββ¬ββββββββ
$0/NR βΆ β ID β WEBSITE β URI β
ββββββββΌβββββββββββββββΌββββββββ€
$0/NR βΆ β 1 β quickref.me β awk β
ββββββββΌβββββββββββββββΌββββββββ€
$0/NR βΆ β 2 β google.com β 25 β
ββββββββ΄βββββββββββββββ΄ββββββββ
# First and last field
awk -F: '{print $1,$NF}' /etc/passwd
# With line number
awk -F: '{print NR, $0}' /etc/passwd
# Second last field
awk -F: '{print $(NF-1)}' /etc/passwd
# Custom string
awk -F: '{print $1 "=" $6}' /etc/passwd
See:
awk 'BEGIN {print "hello world"}' # Prints "hello world"
awk -F: '{print $1}' /etc/passwd # -F: Specify field separator
# /pattern/ Execute actions only for matched pattern
awk -F: '/root/ {print $1}' /etc/passwd
# BEGIN block is executed once at the start
awk -F: 'BEGIN { print "uid"} { print $1 }' /etc/passwd
# END block is executed once at the end
awk -F: '{print $1} END { print "-done-"}' /etc/passwd
awk -F: '$3>30 {print $1}' /etc/passwd
See:
awk 'BEGIN{
while (a++ < 1000)
s=s " ";
print s
}'
See:
awk 'BEGIN {
fruits["mango"] = "yellow";
fruits["orange"] = "orange"
for(fruit in fruits) {
print "The color of " fruit " is " fruits[fruit]
}
}'
See:
# => 5
awk 'BEGIN{print length("hello")}'
# => HELLO
awk 'BEGIN{print toupper("hello")}'
# => hel
awk 'BEGIN{print substr("hello", 1, 3)}'
See:
$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
$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
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 }'
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
ENVIRON β Environment variables
IGNORECASE β Ignore case
CONVFMT β Conversion format
ERRNO β System errors
FIELDWIDTHS β Fixed width fields
awk -v var1="Hello" -v var2="Wold" '
END {print var1, var2}
' </dev/null
awk -v varName="$PWD" '
END {print varName}' </dev/null
{print $1} β First field
$2 == "foo" β Equals
$2 != "foo" β Not equals
"foo" in array β In array
/regex/ β Line matches
!/regex/ β Line not matches
$1 ~ /regex/ β Field matches
$1 !~ /regex/ β Field not matches
($2 <= 4 || $3 < 20) β Or
($1 == 4 && $3 < 20) β And
+ - * / % ++ --
+= -= *= /= %=
== != < > <= >=
awk 'BEGIN {
if ("foo" ~ "^fo+$")
print "Fooey!";
}'
awk 'BEGIN {
if ("boo" !~ "^fo+$")
print "Boo!";
}'
awk 'BEGIN {
assoc["foo"] = "bar";
assoc["bar"] = "baz";
if ("foo" in assoc)
print "Fooey!";
}'
index(s,t) β Position in string s where string t occurs, 0 if not found
length(s) β Length of string s (or $0 if no arg)
rand β Random number between 0 and 1
substr(s,index,len) β Return len-char substring of s that begins at index (counted from 1)
srand β Set seed for rand and return previous seed
int(x) β Truncate x to integer value
split(s,a,fs) β Split string s into array a split by fs, returning length of a
match(s,r) β Position in string s where regex r occurs, or 0 if not found
sub(r,t,s) β Substitute t for first occurrence of regex r in string s (or $0 if s not given)
gsub(r,t,s) β Substitute t for all occurrences of regex r in string s
system(cmd) β Execute cmd and return exit status
tolower(s) β String s to lowercase
toupper(s) β String s to uppercase
getline β Set $0 to next input record from current input file.
awk '
# Returns minimum number
function find_min(num1, num2){
if (num1 < num2)
return num1
return num2
}
# Returns maximum number
function find_max(num1, num2){
if (num1 > num2)
return num1
return num2
}
# Main function
function main(num1, num2){
result = find_min(num1, num2)
print "Minimum =", result
result = find_max(num1, num2)
print "Maximum =", result
}
# Script execution starts here
BEGIN {
main(10, 60)
}
'
awk 'BEGIN {
arr[0] = "foo";
arr[1] = "bar";
print(arr[0]); # => foo
delete arr[0];
print(arr[0]); # => ""
}'
awk 'BEGIN {
assoc["foo"] = "bar";
assoc["bar"] = "baz";
print("baz" in assoc); # => 0
print("foo" in assoc); # => 1
}'
awk 'BEGIN {
split("foo:bar:baz", arr, ":");
for (key in arr)
print arr[key];
}'
awk 'BEGIN {
arr[0] = 3
arr[1] = 2
arr[2] = 4
n = asort(arr)
for (i = 1; i <= n ; i++)
print(arr[i])
}'
awk 'BEGIN {
multidim[0,0] = "foo";
multidim[0,1] = "bar";
multidim[1,0] = "baz";
multidim[1,1] = "boo";
}'
awk 'BEGIN {
array[1,2]=3;
array[2,3]=5;
for (comb in array) {
split(comb,sep,SUBSEP);
print sep[1], sep[2],
array[sep[1],sep[2]]
}
}'
awk -v count=2 'BEGIN {
if (count == 1)
print "Yes";
else
print "Huh?";
}'
awk -v count=2 'BEGIN {
print (count==1) ? "Yes" : "Huh?";
}'
awk 'BEGIN {
assoc["foo"] = "bar";
assoc["bar"] = "baz";
if ("foo" in assoc)
print "Fooey!";
}'
awk 'BEGIN {
assoc["foo"] = "bar";
assoc["bar"] = "baz";
if ("Huh" in assoc == 0 )
print "Huh!";
}'
awk -F: '{
switch (NR * 2 + 1) {
case 3:
case "11":
print NR - 1
break
case /2[[:digit:]]+/:
print NR
default:
print NR + 1
case -1:
print NR * -1
}
}' /etc/passwd
awk 'BEGIN {
for (i = 0; i < 10; i++)
print "i=" i;
}'
awk 'BEGIN {
for (i = 1; i <= 100; i *= 2)
print i
}'
awk 'BEGIN {
assoc["key1"] = "val1"
assoc["key2"] = "val2"
for (key in assoc)
print assoc[key];
}'
awk 'BEGIN {
for (argnum in ARGV)
print ARGV[argnum];
}' a b c
awk -F: '{ x[NR] = $0 }
END {
for (i = NR; i > 0; i--)
print x[i]
}
' /etc/passwd
awk -F: '{
for (i = NF; i > 0; i--)
printf("%s ",$i);
print ""
}' /etc/passwd
awk -F: '{
s=0;
for (i = 1; i <= NF; i++)
s += $i;
print s
}' /etc/passwd
awk -F: '
{for (i = 1; i <= NF; i++)
s += $i;
};
END{print s}
' /etc/passwd
awk 'BEGIN {
while (a < 10) {
print "- " " concatenation: " a
a++;
}
}'
awk '{
i = 1
do {
print $0
i++
} while (i <= 5)
}' /etc/passwd
awk 'BEGIN {
break_num = 5
for (i = 0; i < 10; i++) {
print i
if (i == break_num)
break
}
}'
awk 'BEGIN {
for (x = 0; x <= 10; x++) {
if (x == 5 || x == 6)
continue
printf "%d ", x
}
print ""
}'
awk 'BEGIN{printf "|%10s|\n", "hello"}'
| hello|
awk 'BEGIN{printf "|%-10s|\n", "hello"}'
|hello |
c β ASCII character
d β Decimal integer
e, E, f β Floating-point format
o β Unsigned octal value
s β String
% β Literal %
awk -F: '{
printf "%-10s %s\n", $1, $(NF-1)
}' /etc/passwd | head -n 3
Outputs
root /root
bin /bin
daemon /sbin
awk -F: 'BEGIN {
printf "%-10s %s\n", "User", "Home"
printf "%-10s %s\n", "----","----"}
{ printf "%-10s %s\n", $1, $(NF-1) }
' /etc/passwd | head -n 5
Outputs
User Home
---- ----
root /root
bin /bin
daemon /sbin
\ ^ $ . [ ] | ( ) * + ?
\b β Backspace
\f β Form feed
\n β Newline (line feed)
\r β Carriage return
\t β Horizontal tab
\v β Vertical tab
$ cat demo.awk
#!/usr/bin/awk -f
BEGIN { x = 23 }
{ x += 2 }
END { print x }
$ awk -f demo.awk /etc/passwd
69