Processing Text with grep, sed, and awk
grep, sed and awk are the three classic text-processing tools of Unix and Linux. Each one reads text line by line, from files or from standard input, and writes the result to standard output. They are separate programs, not parts of Bash, but almost every Bash script that deals with logs, configuration files, reports or command output uses at least one of them.
Each tool has a different job:
| Tool | Main job | Thinks of a line as |
|---|---|---|
grep | Selects lines that match a pattern | A string to search |
sed | Edits lines: substitutes, deletes, prints selected ranges | A string to transform |
awk | Splits lines into fields and computes with them | A record made of columns |
Knowing which tool fits which job is the main skill this lesson builds. The next three lessons go deeper: lesson 107 covers cut, sort, uniq and wc, lesson 108 covers substitution with sed, and lesson 109 covers column extraction with awk. Lesson 21 already introduced grep in detail.
The Sample Data
All examples in this lesson use the same small log file, app.log:
2026-11-20 08:15:02 INFO web01 login user=ana ms=120
2026-11-20 08:15:09 WARN web02 slow_query user=bo ms=950
2026-11-20 08:16:30 ERROR web01 db_timeout user=ana ms=3000
2026-11-20 08:17:45 INFO web02 login user=cy ms=98
2026-11-20 08:18:01 ERROR web02 db_timeout user=bo ms=3001
2026-11-20 08:19:12 INFO web01 logout user=ana ms=15
Each line has seven fields separated by spaces: date, time, level, host, event, user and duration in milliseconds.
How the Three Tools Process Text
All three tools follow the same basic model, sometimes called a stream filter:
- Read one line of input.
- Decide what to do with it, based on the program given on the command line.
- Write output (or nothing) for that line.
- Repeat until the input ends.
Because they work one line at a time, they handle files of any size without loading them into memory, and they fit naturally into pipelines (lesson 61): the output of one tool becomes the input of the next.
When a file name is given, the tool reads that file. Without a file name, it reads standard input:
printf 'b\na\n' | sed 's/a/A/'
b
A
grep: Selecting Lines
grep prints the lines that match a pattern and drops the rest. It never changes the content of a line.
grep ERROR app.log
2026-11-20 08:16:30 ERROR web01 db_timeout user=ana ms=3000
2026-11-20 08:18:01 ERROR web02 db_timeout user=bo ms=3001
A few options cover most daily use:
grep -c ERROR app.log # count matching lines
grep -v INFO app.log # print lines that do NOT match
grep -n -w web01 app.log # whole word only, with line numbers
grep -E 'WARN|ERROR' app.log # extended regular expression with alternation
The -n -w web01 search prints:
1:2026-11-20 08:15:02 INFO web01 login user=ana ms=120
3:2026-11-20 08:16:30 ERROR web01 db_timeout user=ana ms=3000
6:2026-11-20 08:19:12 INFO web01 logout user=ana ms=15
grep -o prints only the matching part of each line instead of the whole line, which turns grep into a small extraction tool:
grep -o 'user=[a-z]*' app.log | sort | uniq -c
3 user=ana
2 user=bo
1 user=cy
grep in Conditions
grep reports through its exit status whether anything matched. This makes it the usual choice for "does this file contain X?" tests:
| Status | Meaning |
|---|---|
| 0 | At least one line matched |
| 1 | No line matched |
| 2 | An error occurred, such as a missing file |
grep -q CRIT app.log; echo "status $?"
grep -q ERROR app.log; echo "status $?"
grep x nofile; echo "status $?"
status 1
status 0
grep: nofile: No such file or directory
status 2
-q (quiet) prints nothing and only sets the status, so it is ideal inside if:
if grep -q ERROR app.log; then
echo "Errors found"
fi
sed: Editing Lines
sed is a stream editor. It applies editing commands to each line and prints the result. By default it prints every line, changed or not, so it is used to transform text rather than to filter it.
The most common command is s, substitute:
sed 's/web0/server-/' app.log
2026-11-20 08:15:02 INFO server-1 login user=ana ms=120
2026-11-20 08:15:09 WARN server-2 slow_query user=bo ms=950
2026-11-20 08:16:30 ERROR server-1 db_timeout user=ana ms=3000
2026-11-20 08:17:45 INFO server-2 login user=cy ms=98
2026-11-20 08:18:01 ERROR server-2 db_timeout user=bo ms=3001
2026-11-20 08:19:12 INFO server-1 logout user=ana ms=15
The program s/web0/server-/ reads as "substitute the first web0 on each line with server-". The file itself is not changed; sed only writes the edited copy to standard output. Lesson 108 covers flags such as g, in-place editing with -i, and special characters.
Printing and Deleting Lines
sed can also choose lines by number or by pattern. With -n, automatic printing is turned off and only lines printed explicitly with p appear:
sed -n '2,3p' app.log
2026-11-20 08:15:09 WARN web02 slow_query user=bo ms=950
2026-11-20 08:16:30 ERROR web01 db_timeout user=ana ms=3000
The d command deletes the selected lines and prints the rest:
sed '/INFO/d' app.log
2026-11-20 08:15:09 WARN web02 slow_query user=bo ms=950
2026-11-20 08:16:30 ERROR web01 db_timeout user=ana ms=3000
2026-11-20 08:18:01 ERROR web02 db_timeout user=bo ms=3001
Combining -n with the p flag of s prints only the lines where a substitution happened:
sed -n 's/ERROR/E!/p' app.log
2026-11-20 08:16:30 E! web01 db_timeout user=ana ms=3000
2026-11-20 08:18:01 E! web02 db_timeout user=bo ms=3001
Unlike grep, sed does not use its exit status to report matches. A substitution that changes nothing still returns 0:
sed 's/CRIT/X/' app.log > /dev/null; echo "status $?"
status 0
awk: Working with Fields
awk is a small programming language built for column-based text. It splits each line into fields, using runs of spaces and tabs as separators by default, and names them $1, $2, $3 and so on. $0 is the whole line.
awk '{ print $3, $4 }' app.log
INFO web01
WARN web02
ERROR web01
INFO web02
ERROR web02
INFO web01
An awk program is a list of pattern { action } pairs. The action runs for each line where the pattern is true:
awk '$3 == "ERROR" { print $2, $5 }' app.log
08:16:30 db_timeout
08:18:01 db_timeout
Here the pattern compares the third field with the string ERROR. Unlike grep ERROR, this cannot accidentally match a line where ERROR appears in some other field.
Calculations and the END Block
awk has variables and arithmetic. An END block runs once after the last line, which makes counting and totaling straightforward:
awk '$3 == "ERROR" { n++ } END { print n " errors" }' app.log
2 errors
Variables start empty, which acts as 0 in arithmetic but prints as an empty string. If no line matches, print n prints an empty line; print n+0 forces a number and prints 0:
awk '$3 == "CRIT" { n++ } END { print n+0 }' app.log
0
The duration field looks like ms=120. awk's split function breaks it at = into an array, and the second piece is the number:
awk '{ split($7, kv, "="); total += kv[2] } END { print "total ms:", total }' app.log
total ms: 7184
awk also has associative arrays, so it can group values by a key. This computes the number of requests and the average duration per host:
awk '{ sub(/ms=/, "", $7); sum[$4] += $7; cnt[$4]++ }
END { for (h in sum) printf "%s %d requests, avg %.1f ms\n", h, cnt[h], sum[h]/cnt[h] }' app.log | sort
web01 3 requests, avg 1045.0 ms
web02 3 requests, avg 1349.7 ms
sub(/ms=/, "", $7) removes the ms= prefix from field 7. sum[$4] and cnt[$4] use the host name as the key. In the END block, for (h in sum) visits each key, in an order awk does not guarantee, which is why the output goes through sort.
awk also keeps a line counter, NR. A pattern of NR == 3 selects the third line, and NR in the END block is the total number of lines:
awk 'NR == 3' app.log
awk 'END { print NR " lines" }' app.log
2026-11-20 08:16:30 ERROR web01 db_timeout user=ana ms=3000
6 lines
A pattern without an action prints the matching line, as the first command shows.
Choosing the Right Tool
Many tasks can be done with any of the three. Counting error lines is one example:
grep -c ERROR app.log
sed -n '/ERROR/p' app.log | wc -l
awk '/ERROR/ { n++ } END { print n }' app.log
All three print 2. The simplest one, grep -c, is the clearest choice here. A rough guide:
- Find or filter lines by a pattern:
grep. - Test whether a match exists:
grep -qin anif. - Replace text, delete lines, or print a range of lines:
sed. - Work with columns, compare a specific field, compute totals, averages or counts per key:
awk. - Reformat output into a new layout:
awkwithprintf.
When a task grows beyond a single line of awk or needs complex logic, a full programming language such as Python is usually easier to maintain.
Combining the Tools in Pipelines
The tools are designed to be chained. Each step does one simple thing:
grep ERROR app.log | awk '{ print $4 }' | sort | uniq -c
1 web01
1 web02
grep ERRORkeeps only error lines.awk '{ print $4 }'keeps only the host column.sortgroups identical hosts together.uniq -ccounts each group (lesson 107).
sed often prepares text for awk by removing noise. Here it strips the user= and ms= prefixes, and awk then selects every line that is not INFO:
sed 's/user=//; s/ms=//' app.log | awk '$3 != "INFO" { print $6, $7 }'
bo 950
ana 3000
bo 3001
The semicolon inside the sed program separates two commands, both applied to each line.
Quoting the Programs
sed and awk programs contain characters that Bash would otherwise interpret: $, spaces, *, { }. Always wrap the program in single quotes so Bash passes it unchanged.
With double quotes, Bash expands $3 before awk sees it. In a script run without arguments, $3 is empty, so awk receives { print } and prints whole lines:
awk "{ print $3 }" app.log | head -2
2026-11-20 08:15:02 INFO web01 login user=ana ms=120
2026-11-20 08:15:09 WARN web02 slow_query user=bo ms=950
Passing Shell Variables
To use a Bash variable as a pattern, quote it for grep. For awk, pass it with -v instead of putting it inside the program text:
level=ERROR
grep -- "$level" app.log | wc -l
awk -v lvl="$level" '$3 == lvl { print $5 }' app.log
2
db_timeout
db_timeout
-- tells grep that what follows is the pattern even if it starts with a dash. -v lvl="$level" creates an awk variable named lvl. This keeps the awk program in single quotes and avoids the quoting problems of splicing shell text into it. Passing variables into sed has its own traps with slashes and special characters, covered in lesson 108.
Versions and Portability
The examples in this lesson use only standard features and were run with GNU grep 3.11, GNU sed 4.9 and mawk 1.3.4 (the default awk on Debian and Ubuntu). Other systems may provide GNU awk (gawk) or BSD versions of these tools, as on macOS. Basic syntax such as s/old/new/, -n, p, d, field variables, NR, END, split, sub and associative arrays works the same everywhere, but some options differ, such as sed -i (lesson 108) and grep -o and -w, which are common extensions rather than part of the POSIX standard.