awk#
“Many, many people use
awkonly to do one thing—to pick a single field out of an input stream.”How Linux Works 11.10.2
Basic Usage#
Field Selection#
Print specific columns using $N.
# Print the 5th field
ls -l | awk '{print $5}'Pattern Search#
Filter lines matching a pattern before performing an action.
# Print the 5th field of lines containing "log"
ls -l | awk '/log/ {print $5}'Built-in Variables#
NR (Number of Records)#
Represents the current line number.
- Display line numbers:
awk '{print NR, $0}' file.txt - Filter by line number:
# Print only odd-numbered lines awk 'NR % 2 == 1' file.txt
NF (Number of Fields)#
Represents the total number of fields in the current record.
- Print the last field:
awk '{print $NF}' file.txt