Learn AWK: 25 Examples

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.

Example 1: Print Entire File

Print all lines of a file

awk '{print}' filename.txt

Input:

John Doe 25 Engineer
Jane Smith 30 Designer

Output:

John Doe 25 Engineer
Jane Smith 30 Designer
Example 2: Print Specific Columns

Print first and third columns

awk '{print $1, $3}' filename.txt

Input:

John Doe 25 Engineer
Jane Smith 30 Designer

Output:

John 25
Jane 30
Example 3: Custom Separators

Use colon as input separator, comma as output separator

awk -F: 'BEGIN{OFS=","} {print $1, $3}' /etc/passwd

Input (sample from /etc/passwd):

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin

Output:

root,0
daemon,1
Example 4: Print Lines Containing Pattern

Print lines containing "error"

awk '/error/' logfile.txt

Input:

INFO: Process started
ERROR: File not found
DEBUG: Connecting to server
ERROR: Connection timeout

Output:

ERROR: File not found
ERROR: Connection timeout
Example 5: Print Lines NOT Containing Pattern

Print lines that don't contain "success"

awk '!/success/' logfile.txt

Input:

INFO: Process started
SUCCESS: File uploaded
DEBUG: Connecting to server
ERROR: Connection failed

Output:

INFO: Process started
DEBUG: Connecting to server
ERROR: Connection failed
Example 6: Field Comparison

Print lines where second field > 100

awk '$2 > 100' data.txt

Input:

item1 50
item2 150
item3 75

Output:

item2 150
Example 7: Print Line Numbers

Print line number and content

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

Input:

first line
second line
third line

Output:

1 first line
2 second line
3 third line
Example 8: Print File Name and Line Count

Count lines in a file

awk 'END{print FILENAME, NR}' filename.txt

Input (filename.txt with 3 lines):

line 1
line 2
line 3

Output:

filename.txt 3
Example 9: Using NF (Number of Fields)

Print last field of each line

awk '{print $NF}' filename.txt

Input:

apple banana cherry
dog cat bird

Output:

cherry
bird
Example 10: Add Header and Footer

Add header and count lines

awk 'BEGIN{print "--- START ---"} {print} END{print "--- END ---\nTotal lines:", NR}' file.txt

Input:

line 1
line 2

Output:

--- START ---
line 1
line 2
--- END ---
Total lines: 2
Example 11: Calculate Sum

Sum numbers in second column

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

Input:

A 10
B 20
C 30

Output:

Total: 60
Example 12: String Concatenation

Combine first and last name

awk '{print $1 " " $2}' names.txt

Input:

John Doe
Jane Smith

Output:

John Doe
Jane Smith
Example 13: String Length

Print length of first field

awk '{print $1, length($1)}' words.txt

Input:

hello
world
awk

Output:

hello 5
world 5
awk 3