How to process text with awk in Linux
· Category: Linux
Short answer
awk is a text-processing tool that operates on fields and records, ideal for extracting and transforming columnar data.
Steps
- Print a column:
awk '{print $1}' file.txt
- Specify a delimiter:
awk -F',' '{print $2}' data.csv
- Filter rows:
awk '$3 > 100 {print $0}' data.txt
- Sum a column:
awk '{sum += $1} END {print sum}' numbers.txt
Tips
awkprocesses line by line;BEGINandENDblocks run before and after.- Use
-vto pass shell variables intoawk. awkis faster than Python for simple columnar transformations.
Common issues
- Whitespace delimiter:
awktreats multiple spaces as one by default. $0is the whole line;$1is the first field.