The awk command is a versatile text-processing tool used in Unix-based systems for manipulating and analyzing text files, particularly for extracting and processing fields within lines based on patterns.
Basic Format
awk 'pattern {action}' file
Key Expressions
BEGIN
Defines actions to be taken before file processing begins.
END
Defines actions to be taken after all file processing is done.
NR
Represents the total number of records being processed or line number.
NF
Number of fields within the current record.
$0
Represents the entire line.
$1, $2, ... , $n
Represents the 1st, 2nd, ..., nth field in the line.
FS
The Input Field Separator Variable. Default is white space.
OFS
The Output Field Separator Variable.
FILENAME
The name of the file being read.
Examples
awk '{print}' file
Prints every line from 'file'.
awk '/pattern/ {print}' file
Prints every line matching 'pattern' from 'file'.
awk '!/pattern/ {print}' file
Prints every line not matching 'pattern' from 'file'.
awk '{print $1, $3}' file
Prints the 1st and 3rd field of every line from 'file'.
awk 'BEGIN {FS=":"} {print $1}' file
Changes field separator to ':' and prints first field.
awk '{print NR, $0}' file
Prints line number along with each line.
awk 'END {print NR}' file
Prints total number of lines in 'file'.
awk '{sum += $1} END {print sum}' file
Sums up the first field of all lines and prints total.
Playground
Use BashSenpai to generate a command from a text prompt: