Master text processing with practical AWK examples
AWK is a powerful text processing language that is particularly useful for manipulating structured data and generating reports. Below you'll find 25 practical examples organized by category.
awk '{print}' filename.txt
John Doe 25 Engineer Jane Smith 30 Designer
John Doe 25 Engineer Jane Smith 30 Designer
awk '{print $1, $3}' filename.txt
John Doe 25 Engineer Jane Smith 30 Designer
John 25 Jane 30
awk -F: 'BEGIN{OFS=","} {print $1, $3}' /etc/passwd
root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
root,0 daemon,1
awk '/error/' logfile.txt
INFO: Process started ERROR: File not found DEBUG: Connecting to server ERROR: Connection timeout
ERROR: File not found ERROR: Connection timeout
awk '!/success/' logfile.txt
INFO: Process started SUCCESS: File uploaded DEBUG: Connecting to server ERROR: Connection failed
INFO: Process started DEBUG: Connecting to server ERROR: Connection failed
awk '$2 > 100' data.txt
item1 50 item2 150 item3 75
item2 150
awk '{print NR, $0}' filename.txt
first line second line third line
1 first line 2 second line 3 third line
awk 'END{print FILENAME, NR}' filename.txt
line 1 line 2 line 3
filename.txt 3
awk '{print $NF}' filename.txt
apple banana cherry dog cat bird
cherry bird
awk 'BEGIN{print "--- START ---"} {print} END{print "--- END ---\nTotal lines:", NR}' file.txt
line 1 line 2
--- START --- line 1 line 2 --- END --- Total lines: 2
awk '{sum += $2} END{print "Total:", sum}' data.txt
A 10 B 20 C 30
Total: 60
awk '{print $1 " " $2}' names.txt
John Doe Jane Smith
John Doe Jane Smith
awk '{print $1, length($1)}' words.txt
hello world awk
hello 5 world 5 awk 3