awk Column and text processing
Light · Postcard
102 × 152 mm · PDF
Dark · Postcard
102 × 152 mm · PDF
Ink saver · Postcard
102 × 152 mm · PDF
Light · A4 landscape
297 × 210 mm · PDF
Dark · A4 landscape
297 × 210 mm · PDF
Ink saver · A4 landscape
297 × 210 mm · PDF
Light · A3 landscape
420 × 297 mm · PDF
Dark · A3 landscape
420 × 297 mm · PDF
Ink saver · A3 landscape
420 × 297 mm · PDF
Start here
awk '{print $1}' <file>
awk -F: '{print $1}' <file>
awk '/<regex>/' <file>
awk '$3 > 10' <file>
awk '{s+=$2} END {print s}' <file>
awk 'NR==1' <file>
awk -v n=<val> '$1==n' <file>
awk '{print NF}' <file>
Concepts
- BEGIN once, before input
- Split line $0, $1 ... $NF
- Action { ... } per record
- END once, totals
Running
awk '<prog>' <file>
awk -f <script.awk> <file>
awk -F<sep> '<prog>'
awk -v <var>=<val> '<prog>'
<cmd> | awk '<prog>'
awk -F, -v OFS=, '<prog>'
awk -i inplace '<prog>' <file>
awk --csv '<prog>' <file>
Fields & variables
$0$1, $2, $NFNRNFFNRFS / OFSRS / ORSFILENAME$1=$1ENVIRON["<name>"]
ARGV[<n>] / ARGC
Patterns
BEGIN { ... }END { ... }/<regex>/!/<regex>/
$<n> ~ /<regex>/
$<n> !~ /<regex>/
<expr> && <expr>
NR==<a>, NR==<b>
NR % 2BEGINFILE { ... }
Actions & control
print $1, $3{ s += $2 }if (<cond>) ... else ...
for (i = 1; i <= NF; i++)
for (<key> in <arr>)
while (<cond>) { ... }
nextexit [<code>]
getline <var> < <file>
system("<cmd>")
Functions
length(<s>)
substr(<s>, <start>, <len>)
index(<s>, <t>)
split(<s>, <arr>, <sep>)
sub(/<re>/, "<new>" [,
<t>])
gsub(/<re>/, "<new>" [,
<t>])
match(<s>, /<re>/)
tolower(<s>) / toupper(<s>)
sprintf("<fmt>", ...)
int(<x>), sqrt(<x>), rand()
gensub(/<re>/, "<new>", "g",
<s>)
asort(<arr>) / asorti(<arr>)
systime() / strftime("<fmt>")
Output
printf "%s\n", $1
printf "%-10s %5.2f\n", $1, $2
print > "<file>"
print >> "<file>"
print | "<cmd>"
print > "/dev/stderr"
Arrays
| Idiom | Meaning |
|---|---|
a[$1]++ |
count each key |
a[$1] += $2 |
sum per key |
!seen[$0]++ |
first occurrence only |
(k in a) |
key exists, no create |
delete a[k] |
remove one element |
delete a |
empty the whole array |
Recipes
awk '{ s += $3 } END { print s, s/NR }' <file>
awk '{ n[$1]++ } END { for (k in n) print n[k], k }' <file> | sort -rn
awk '!seen[$0]++' <file>
awk -F, -v OFS='\t' 'NR > 1 { $1 = $1; print }' <file>
# lookup table first, data secondawk 'NR==FNR { v[$1]=$2; next } $1 in v { print $0, v[$1] }' <a> <b>



