Extracting Columns with awk
awk splits every input line into fields and lets a program select, compare, compute and reformat those fields. That makes it the standard Bash companion for column-based text: reports, logs, the output of commands such as ps, df and ls -l, and files separated by colons, tabs or commas.
Lesson 106 showed where awk fits next to grep and sed. This lesson focuses on columns: how awk splits lines, how to choose and reorder fields, how to filter rows by column values, how to change the separators, and how to compute totals and groups from columns.
The Sample Data
Most examples use sales.txt, a table aligned with spaces:
region product units price
north laptop 3 899.50
south phone 10 299.00
north phone 4 299.00
east tablet 2 450.00
south laptop 1 899.50
Some examples also use users.txt from lesson 107 (colon-separated, in the /etc/passwd format) and a tab-separated file people.tsv.
How awk Splits a Line
For each input line (called a record), awk:
- Stores the whole line in
$0. - Splits it into fields using the field separator,
FS. - Stores the fields in
$1,$2,$3, and so on. - Sets
NFto the number of fields andNRto the current record number. - Runs every
pattern { action }rule of the program against the line.
The default field separator is a single space, which has a special meaning: fields are separated by runs of spaces and tabs, and leading and trailing blanks are ignored. This is why awk handles aligned tables that confuse cut (lesson 107):
echo ' x y ' | awk '{ print NF, "[" $1 "]" }'
2 [x]
Despite the extra spaces, awk sees exactly two fields, and $1 contains no spaces.
Selecting Columns
By Number
$1 is the first field, $2 the second, and so on. NF holds the number of fields, so $NF is always the last field, whatever the line length:
awk '{ print $1, $NF }' sales.txt
region price
north 899.50
south 299.00
north 299.00
east 450.00
south 899.50
$(NF-1) is the second-to-last field. The parentheses are required, because $NF-1 would mean "the last field minus 1":
awk '{ print $(NF-1) }' sales.txt | head -3
units
3
10
$NF is particularly useful when lines have different numbers of fields:
printf 'a b c\nd e\n' | awk '{ print $NF }'
c
e
NF itself tells how many fields a line has:
awk '{ print NF ": " $0 }' sales.txt | head -2
4: region product units price
4: north laptop 3 899.50
A field number beyond NF is simply empty; it is not an error:
echo 'a b' | awk '{ print "[" $5 "]", NF }'
[] 2
Commas, Spaces and Concatenation
In print, a comma inserts the output field separator (a space by default). Writing values next to each other with no comma joins them directly:
awk 'NR == 2 { print $1, $2; print $1 $2; print $1 "-" $2 }' sales.txt
north laptop
northlaptop
north-laptop
Forgetting the comma is a common reason for columns running together in the output.
Reordering Columns
Unlike cut, awk prints fields in whatever order the program lists them:
awk '{ print $3, $1 }' sales.txt | head -3
units region
3 north
10 south
Skipping the Header Line
NR is the record number, starting at 1. A pattern of NR > 1 skips the first line:
awk 'NR > 1 { print $2 }' sales.txt
laptop
phone
phone
tablet
laptop
The next statement stops processing the current line and moves to the next one. It lets a header get its own treatment:
awk 'NR == 1 { printf "%-6s %-7s %8s\n", $1, $2, "total"; next }
{ printf "%-6s %-7s %8.2f\n", $1, $2, $3 * $4 }' sales.txt
region product total
north laptop 2698.50
south phone 2990.00
north phone 1196.00
east tablet 900.00
south laptop 899.50
The first rule prints a header and calls next, so the second rule never sees line 1. next is also a simple way to skip comment lines:
awk '/^#/ { next } { print $1 }' app.conf | head -3
host=localhost
port=8080
debug=true
Filtering Rows by Column Values
The pattern part of a rule can test any field.
Comparisons
awk compares fields as numbers when both sides look like numbers, and as strings otherwise:
awk 'NR > 1 && $3 >= 3 { print $1, $2, $3 }' sales.txt
awk '$1 == "north"' sales.txt
north laptop 3
south phone 10
north phone 4
north laptop 3 899.50
north phone 4 299.00
A rule with a pattern and no action prints the whole line, unchanged, as the second command shows.
The difference between number and string comparison matters:
echo '10 9' | awk '{ print ($1 > $2) }'
echo '10 9' | awk '{ a = $1 ""; b = $2 ""; print (a > b) }'
1
0
Both fields look numeric, so the first comparison is numeric and true (1). Appending an empty string, "", turns each value into a string, and as strings "10" sorts before "9", so the second comparison is false (0).
Regular Expressions on a Field
~ tests whether a field matches a regular expression, and !~ whether it does not:
awk '$2 ~ /^(laptop|tablet)$/ { print $1, $2 }' sales.txt
north laptop
east tablet
south laptop
The anchors ^ and $ make the expression match the whole field. Without them, /lap/ would match any product containing lap.
Combining Conditions
&& (and), || (or) and ! (not) combine conditions. Several rules can also be listed, and each line is checked against every rule:
awk 'NR == 1 { next } $3 > 3 { print "many:", $2 } $3 <= 3 { print "few:", $2 }' sales.txt
few: laptop
many: phone
many: phone
few: tablet
few: laptop
Computing with Columns
Fields can be used in arithmetic directly. This computes the revenue of each row:
awk 'NR > 1 { print $1, $2, $3 * $4 }' sales.txt
north laptop 2698.5
south phone 2990
north phone 1196
east tablet 900
south laptop 899.5
print shows numbers in a compact default format, which drops trailing zeros. printf controls the format exactly:
awk 'NR > 1 { printf "%-6s %-7s %8.2f\n", $1, $2, $3 * $4 }' sales.txt
north laptop 2698.50
south phone 2990.00
north phone 1196.00
east tablet 900.00
south laptop 899.50
| Format | Meaning |
|---|---|
%s | String |
%-6s | String, left-aligned in 6 characters |
%d | Integer |
%8.2f | Number, right-aligned in 8 characters, 2 decimals |
\n | Newline (printf does not add one automatically) |
awk's division is floating point. int() truncates, and % gives the remainder:
awk 'BEGIN { print 7 / 2, int(7 / 2), 7 % 2 }'
3.5 3 1
A BEGIN block runs before any input is read; with only a BEGIN block, awk does not read input at all.
Totals and Averages
Variables start empty (0 in arithmetic), so accumulating needs no initialization. The END block runs after the last line:
awk 'NR > 1 { units += $3; revenue += $3 * $4; n++ }
END { printf "rows=%d units=%d revenue=%.2f avg=%.2f\n", n, units, revenue, revenue / n }' sales.txt
rows=5 units=20 revenue=8684.00 avg=1736.80
Maximum Value
awk 'NR > 1 && ($3 > max || max == "") { max = $3; who = $1 " " $2 }
END { print "max units:", max, "(" who ")" }' sales.txt
max units: 10 (south phone)
The max == "" test makes the first data row set the starting maximum, so the code also works when all values are negative.
Grouping by a Column
awk arrays are associative: the index can be any string. Using a column as the index groups rows by that column:
awk 'NR > 1 { rev[$1] += $3 * $4 }
END { for (r in rev) printf "%s %.2f\n", r, rev[r] }' sales.txt | sort -k2,2nr
north 3894.50
south 3889.50
east 900.00
for (r in rev) visits the keys in no particular order, so the output is piped to sort (lesson 107) to rank regions by revenue.
A related idiom prints each value of a column only the first time it appears:
awk 'NR > 1 && !seen[$2]++ { print $2 }' sales.txt
laptop
phone
tablet
seen[$2]++ returns the old count, which is 0 (false) the first time a product appears, so !seen[$2]++ is true only once per product. Unlike sort -u, this keeps the original order.
Changing the Field Separator
-F and FS
-F sets the input field separator. For colon-separated data:
awk -F: '{ print $1, $7 }' users.txt
ana /bin/bash
bo /bin/zsh
cy /bin/bash
dee /usr/sbin/nologin
Setting FS in a BEGIN block does the same thing inside the program:
awk 'BEGIN { FS = ":" } { print $1 }' users.txt | head -2
ana
bo
Tab-Separated Data
Tab-separated files often contain spaces inside values. The default separator would split Ana Silva and New York into two fields each, so the separator must be a tab:
awk -F'\t' '{ print $2 " | " $3 }' people.tsv
name | city
Ana Silva | Lisbon
Bo | New York
With the default separator, awk '{ print $2 }' people.tsv prints name, Ana and Bo, cutting the full name in half.
A Single Space and Regular Expressions
-F' ' is the same as the default: runs of blanks. Any separator longer than one character is treated as a regular expression, so -F'[ ]' means "exactly one space", and consecutive spaces then create empty fields:
echo 'a b' | awk -F' ' '{ print NF }'
echo 'a b' | awk -F'[ ]' '{ print NF }'
2
3
A regular expression separator can accept several different delimiters at once, with optional spaces around them:
echo 'a, b;c ,d' | awk -F' *[,;] *' '{ for (i = 1; i <= NF; i++) printf "[%s]", $i; print "" }'
[a][b][c][d]
The loop from 1 to NF visits every field, which is the general way to process all columns of a line.
The Output Field Separator
OFS is the separator that print places between comma-separated values. It can be set with -v:
awk -F: -v OFS=' | ' '{ print $1, $7 }' users.txt | head -2
ana | /bin/bash
bo | /bin/zsh
Setting OFS does not change $0 by itself. awk rebuilds $0 with the new separator only when a field is assigned. The idiom $1 = $1 forces that rebuild, which converts a file from one separator to another:
awk -F: -v OFS=',' '{ print }' users.txt | head -1
awk -F: -v OFS=',' '{ $1 = $1; print }' users.txt | head -1
ana:x:1001:1001:Ana Silva:/home/ana:/bin/bash
ana,x,1001,1001,Ana Silva,/home/ana,/bin/bash
Modifying Fields
Assigning to a field changes it and rebuilds $0, joining all fields with OFS. This raises the price column by 10 percent:
awk 'NR > 1 { $4 = $4 * 1.1; print }' sales.txt | head -2
north laptop 3 989.45
south phone 10 328.9
The original alignment is gone, because the rebuilt line uses single spaces. Assigning to a field beyond NF extends the line with empty fields:
echo 'a b' | awk '{ $4 = "d"; print; print NF }'
a b d
4
Passing Shell Values to awk
Shell variables are not visible inside a single-quoted awk program. Writing $min there means something else entirely: min is an awk variable that has never been set, so it is 0, and $min is $0, the whole line:
awk 'NR > 1 && $3 >= $min { print $2 }' sales.txt
This prints nothing, because each number is compared with the text of its own line. The correct way is -v, which creates an awk variable before the program starts:
min=3
awk -v min="$min" 'NR > 1 && $3 >= min { print $2 }' sales.txt
laptop
phone
phone
Exported environment variables are also available through the ENVIRON array:
export REGION=south
awk '$1 == ENVIRON["REGION"] { print $2 }' sales.txt
phone
laptop
One difference: -v processes backslash escapes in the value (so \t becomes a tab), while ENVIRON passes the value unchanged.
Useful String Functions
| Function | Returns |
|---|---|
length(s) | Number of characters in s |
substr(s, start, len) | Part of s, starting at position start (from 1) |
index(s, t) | Position of t in s, or 0 |
toupper(s), tolower(s) | s in upper or lower case |
split(s, arr, sep) | Splits s into arr, returns the number of pieces |
sub(re, repl, target) | Replaces the first match in target |
gsub(re, repl, target) | Replaces all matches in target |
awk 'NR > 1 { print toupper($1), length($2), substr($2, 1, 3) }' sales.txt | head -2
NORTH 6 lap
SOUTH 5 pho
Working with Command Output
Many system commands print aligned columns, which awk reads naturally. These examples use sample text in the same layout as ps and df output, so the results are predictable.
Processes using more than 1 percent CPU, printed as PID and user:
printf 'USER PID %%CPU\nroot 1 0.0\nana 42 12.5\nbo 77 3.1\n' |
awk 'NR > 1 && $3 > 1.0 { print $2, $1 }'
42 ana
77 bo
File systems more than 80 percent full:
printf 'Filesystem Size Used Avail Use%% Mounted\n/dev/sda1 50G 45G 5G 90%% /\n/dev/sdb1 100G 20G 80G 20%% /data\n' |
awk 'NR > 1 { use = $5; sub(/%/, "", use); if (use + 0 > 80) print $6, $5 }'
/ 90%
The percentage field 90% is copied to a variable, the % sign is removed with sub, and use + 0 forces a numeric comparison. On a real system, the same programs work with ps aux and df -h, though the column positions should be checked against the actual header first.
Several Files
When awk reads several files, NR keeps counting across all of them, while FNR restarts at 1 for each file and FILENAME holds the current name:
awk 'FNR == 1 { print FILENAME, NR, FNR }' sales.txt users.txt
sales.txt 1 1
users.txt 7 1
users.txt begins at overall record 7, because sales.txt has six lines.
The examples in this lesson were run with mawk 1.3.4, the default awk on Debian and Ubuntu, in Bash 5.2.21. They use only features defined by POSIX awk, so they also work with GNU awk (gawk) and BSD awk.