logo
search
list

Table of Content

Basic Syntax
Print Fields (and Put Spaces Between Them)
Change the Field Separator (-F / FS)
Patterns, Conditions, and Regex
BEGIN and END (Headers and Totals)
Work with CSV-Style Files
Multiple Files and Pipelines
Useful Built-ins at a Glance
Common Mistakes
When to Use Awk
Quick Cheat Sheet
From Column Output to Shareable Sheets and Reports
FAQ

Awk Command in Linux: Print Fields & Process Text (Ubuntu)

Posted by Algirdas Jasaitis

calendar

2026-07-27

views

880

likes

5

The awk command in Linux is a pattern-scanning and text-processing language. It reads input record by record (usually one line at a time), splits each record into fields (columns), then runs your rules. On Ubuntu you typically get awk as a symlink to an implementation such as mawk or gawk; for the full GNU feature set, install/use gawk.

awk --version 2>/dev/null || awk -W version
man awk
# or, for GNU Awk:
man gawk

Official docs describe AWK as pattern { action } rules: for each input line, matching patterns run their actions. No pattern means “every line”; no action means “print the line.” If you already know your goal, jump to: print fields, -F, patterns, or BEGIN/END. For line search use grep; for substitutions use sed.

Concept illustration of the Linux awk command splitting text into fields ($1, $2, $3) in a terminal
Awk splits each line into fields—print columns with $1…$NF, set separators with -F, and summarize with BEGIN/END.

For a broader Ubuntu terminal quick reference, see the Linux commands cheat sheet.

Basic Syntax

awk [options] 'program' [file...]

No file → read stdin (pipes). Fields default to whitespace-separated:

TokenMeaning
$0Whole line
$1, $2, …Field 1, 2, …
$NFLast field (NF = number of fields)
NRRecord (line) number so far
FS / OFSInput / output field separator
awk '{print $1}' names.txt
echo 'one two three' | awk '{print $2}'
# two

Print Fields (and Put Spaces Between Them)

A classic Ask Ubuntu gotcha: print $5 $1 glues fields with no separator. Use a comma (uses OFS) or an explicit space:

# Stuck together
awk '{print $5 $1}' a.txt

# Space via string
awk '{print $5 " " $1}' a.txt

# Comma → OFS (default is a space); set OFS to a tab
ls -la | awk -v OFS='\t' '{print $5, $1}'

# Or printf for aligned columns
ls -la | awk '{printf "%8s\t%s\n", $5, $1}'

Tip from that thread: prefer stat/find over parsing ls in scripts—ls is for humans.

Change the Field Separator (-F / FS)

# Colon-separated (passwd-style)
awk -F: '{print $1, $7}' /etc/passwd

# Comma CSV-ish
awk -F',' '{print $1, $NF}' data.csv

# Set FS in BEGIN (same idea)
awk 'BEGIN {FS=","} {print $2}' data.csv

Default FS is whitespace (spaces and tabs). For strict single-character separators, -F is the everyday switch.

Patterns, Conditions, and Regex

# Lines matching a regex → print whole line (default action)
awk '/ERROR/' app.log

# Condition on a field
awk '$3 > 100 {print $1, $3}' scores.txt

# Skip header / blank lines
awk 'NR>1 && NF>0 {print $0}' table.tsv

# Invert: lines that do not match
awk '!/DEBUG/' app.log
awk '{
  if ($1 == "FAIL") print "bad:", $0
  else if ($1 == "OK") print "good:", $2
}' results.txt

BEGIN and END (Headers and Totals)

BEGIN runs before any input; END runs after all input:

awk '
BEGIN { print "Directory Report" }
NF > 9 { print $9, "->", $NF }
END { print "Done. Lines:", NR }
' listing.txt

Sum a column (very common one-liner):

awk '{s += $1} END {print s}' numbers.txt
awk '{s += $3} END {print "avg =", s/NR}' data.txt

Count lines like wc -l:

awk 'END {print NR}' file.txt

Work with CSV-Style Files

Awk is not a full CSV parser (quoted commas need care), but it handles simple delimiter files well:

# Print column names (first line)
awk -F',' 'NR==1 {print; exit}' file.csv

# Print selected columns
awk -F',' '{print $2, $4}' file.csv

# Filter rows
awk -F',' '$3 == "active" {print $1, $2}' users.csv

For messy quoted CSV, use a dedicated tool or Python; keep awk for clean TSV/CSV without embedded commas in fields.

Multiple Files and Pipelines

# Process several files; FILENAME / FNR help when needed
awk '{print FILENAME, FNR, $1}' a.log b.log

# Pipeline
df -h | awk 'NR==1 || /\/$/ {print $1, $5, $6}'
ps aux | awk '$3+0 > 5.0 {print $2, $3, $11}'

Ask Ubuntu also discusses reading more than one file in one awk program (ARGV, getline); for most guides, separate files on the command line is enough.

Useful Built-ins at a Glance

VariableRole
NRLines seen so far (across files)
FNRLine number in the current file
NFFields in current line
FS / OFSInput / output field separator
RS / ORSInput / output record separator
FILENAMECurrent file name
awk '{print NR, NF, $1, $NF}' file.txt

Common Mistakes

MistakeFix
print $1 $2 with no spaceUse print $1, $2 or print $1 " " $2
Wrong columns on CSVSet -F',' (or the real delimiter)
Expecting PCREAwk regex is ERE-style; not identical to grep -P
Parsing lsPrefer stat / find for scripts
Need complex CSV quotesUse a real CSV library
Want find-and-replace onlysed may be simpler; use awk when fields matter

When to Use Awk

Choose awk when text is columnar—print fields, set separators, and summarize with BEGIN/END. Prefer grep to find lines and sed for stream substitutions. Typical chain: grep narrows lines → awk extracts fields → redirect or pipe onward.

Quick Cheat Sheet

awk '{print $1}' f              # first field
awk '{print $1, $NF}' f         # first and last
awk -F: '{print $1}' /etc/passwd
awk -v OFS='\t' '{print $1, $2}' f
awk '/pat/' f                   # lines matching pat
awk 'NR>1 {print}' f            # skip header
awk '{s+=$1} END {print s}' f   # sum column 1
awk 'END {print NR}' f          # line count

From Column Output to Shareable Sheets and Reports

awk is excellent for slicing fields and summarizing text in the terminal. Those same results often become a spreadsheet, a status report, or a PDF for review.

WPS Office for Linux is a natural next step there: Spreadsheet for tabular output, Writer for commentary, and PDF when the final file should not move around.

WPS Office Writer on a Linux desktop editing an incident report DOCX with a familiar ribbon toolbar
WPS Writer on Linux: turn setup notes, terminal findings, and troubleshooting steps into a DOCX or PDF that teammates can open easily.
What you need nextWhat WPS gives you
Turn awk output into office-style tables and reportsStrong .docx / .xlsx / .pptx layout fidelity when files move between Linux, Windows, and macOS
One place for notes, sheets, slides, and PDFsFree core suite: Writer, Spreadsheet, Presentation, plus PDF view/edit/convert tools
A familiar desktop UI for switchersRibbon-style apps with a lighter footprint than many heavy suites
A trusted install pathOfficial DEB (Ubuntu/Debian/Mint) and RPM packages from the vendor

Use the official WPS Office for Linux download page, then install the local package with sudo apt install ./wps-office_VERSION_amd64.deb. Keep awk for extraction and summarizing; use WPS when that output needs to be reviewed in a spreadsheet or document.

FAQ

What does the awk command do in Linux?
It processes text by records and fields—print columns, filter rows, and compute simple aggregates without a full programming language.

How do I print the last column?
awk '{print $NF}' file

How do I use a custom delimiter?
awk -F',' '{print $2}' file.csv or set FS in BEGIN.

Why is there no space between printed fields?
print $a $b concatenates. Use a comma (print $a, $b) so OFS is inserted.

Is Ubuntu’s awk the same as gawk?
Not always. Check awk --version / awk -W version. Install gawk when you need GNU extensions.

Where is the official documentation?
Run man awk or man gawk; GNU Awk is documented as a pattern scanning and processing language.

Algirdas Jasaitis

15 years of office industry experience, tech lover and copywriter. Follow me for product reviews, comparisons, and recommendations for new apps and software.