Skip to content

awk

=this.title🔗

= ("[Website](" + this.url + ")") | = ("[Documentation](" + this.docs + ")") | = ("[Reources](" + this.rsc + ")") | Cheatsheet
= ("> " + this.desc-short)

Quick reference cheatsheet

quickref.me

awk_quickref

Collection of AWK one-liners

= ("[Documentation](" + this.docs + ")")

Commands🔗

1
2
3
4
5
awk '{print $2 ", " $1}' <file> # concatenate fields 2 and 1 with string
awk '{print $(NF)}' file # print last column
awk -F'=' {print $2} # use = as field separator
awk -f <awk program> <file> # execute awk program script for file
awk '{print $(NF-2)}' # arithemtic operations

Logic🔗

1
if ( <expr> ) { <cmd> } [else { <cmd> }]

Loops🔗

1
2
for ( i=1; i<=NF; i++ )
  ...

Functions🔗

1
getline [x] # get next line (and save to variable)

Formatting🔗

1
2
printf("%20s",s) # print string with length 20, right-aligned
printf("%-12s",s) # print string with length 12, left-aligned

Maths🔗

1
2
3
4
5
int(3.9) # returns 3
rand() # returns random float 0 <= f < 1
int(rand()*6)+1 # simulate rolling 6-sided die
srand() # seed random number generator, if arg. omitted use curr. time + date\
pi=atan2(0,-1)

Variables🔗

Strings🔗

1
2
3
4
5
6
length() # length of string
index() # position of substring in string, 0 if not found
...
sub(regex,newval[,string]) # replace first occurance
gsub(regex,newval[,string]) # replace all occurances
split(string,array[,regex])

Arrays🔗

Awk arrays are associative (dictionaries). Only one-dimensional arrays supported, multi-dimensional ones can be simulated by nesting arrays. Awk supports

  • Indexed arrays
  • Associative arrays
1
2
a["x"] = 1; a["y"] = 2; a["z"] = 3
for ( <index> in <array> ) {}

There is no easy way to iterate over values in an array.

Special🔗

1
2
3
4
5
6
FS # field separator
OFS # output field separator
RS # record separator
NF # number of fields on a line
NR # number of current record (line)
FILENAME

Redirection and Pipes🔗

Piping into sh

1
2
{ printf("mv %s %s\n", $0, tolower($0)) | "sh" }
END { close("sh") }

Examples🔗

My snippets/scripts

References🔗

Tutorials and courses