Extracting Columns with awk

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 109 of 205

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:

  1. Stores the whole line in $0.
  2. Splits it into fields using the field separator, FS.
  3. Stores the fields in $1, $2, $3, and so on.
  4. Sets NF to the number of fields and NR to the current record number.
  5. 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
FormatMeaning
%sString
%-6sString, left-aligned in 6 characters
%dInteger
%8.2fNumber, right-aligned in 8 characters, 2 decimals
\nNewline (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

FunctionReturns
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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Extracting Columns with awk and get answers drawn from it.

Signed-in readers only.