$linuxjunkies
>

awk(1)

awk is a text processing language that scans files line-by-line, splits records into fields, and performs pattern-action operations.

UbuntuDebianFedoraArch

Synopsis

awk [OPTION]... 'program' [file...]

Description

awk reads input files (or stdin) one line at a time and applies a program consisting of patterns and actions. Each line (record) is split into whitespace-separated fields accessible via $1, $2, etc. Patterns can be regular expressions, expressions, or special blocks like BEGIN and END that run before/after processing.

It's ideal for extracting columns, filtering rows, computing sums, and transforming structured text. Variables and arrays are available, and printf formatting is supported for output control.

Common options

FlagWhat it does
-Fset the field separator (default is whitespace); e.g. -F: for colon-separated files
-vassign a variable before the program runs; e.g. -v var=value
-fread the awk program from a file instead of the command line
-W versionprint the awk version and exit
BEGINpattern that runs once before any input is processed
ENDpattern that runs once after all input is processed
$0the entire current record (line)
$nthe nth field of the current record (1-indexed)
NFthe number of fields in the current record
NRthe current record number (line number)

Examples

print the first field (column) of each line

awk '{print $1}' file.txt

print username and UID from passwd file (colon-separated)

awk -F: '{print $1, $3}' /etc/passwd

print lines where the third field is greater than 50

awk '$3 > 50 {print $1, $3}' data.txt

sum all values in the second column and print the total

awk 'BEGIN {sum=0} {sum+=$2} END {print "Total:", sum}' numbers.txt

count lines containing 'ERROR'

awk '/ERROR/ {count++} END {print count}' logfile.log

prefix each line with its line number

awk '{print NR, $0}' file.txt

print first three fields separated by pipes instead of spaces

awk -v OFS='|' '{print $1, $2, $3}' file.txt

join two files by first column using an associative array

awk 'NR==FNR {a[$1]=$2; next} $1 in a {print $1, a[$1], $2}' file1.txt file2.txt

Related commands