typestar

awk in Bash

Column math on whitespace-split records.

data='alice 42 admin
bob 17 user
carol 99 admin'

# awk splits on whitespace; $2 is the second column
echo "$data" | awk '{ print $1, $2 * 2 }'

# patterns select rows before actions run
echo "$data" | awk '$2 > 20 { print $1 }'
echo "$data" | awk '$3 == "admin" { count++ } END { print count }'

# and it sums like a spreadsheet
echo "$data" | awk '{ total += $2 } END { print "total", total }'

How it works

  1. $1, $2 are columns; actions run per line.
  2. A leading pattern like $2 > 20 selects rows first.
  3. END blocks report totals after the last line.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
395
Tokens
36
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 29 seconds.

Type this snippet

Step 3 of 3 in Text tools, step 21 of 26 in Language basics.

← Previous Next →