Processing Text with grep, sed, and awk

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 106 of 205

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:

ToolMain jobThinks of a line as
grepSelects lines that match a patternA string to search
sedEdits lines: substitutes, deletes, prints selected rangesA string to transform
awkSplits lines into fields and computes with themA 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:

  1. Read one line of input.
  2. Decide what to do with it, based on the program given on the command line.
  3. Write output (or nothing) for that line.
  4. 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:

StatusMeaning
0At least one line matched
1No line matched
2An 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 -q in an if.
  • 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: awk with printf.

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
  1. grep ERROR keeps only error lines.
  2. awk '{ print $4 }' keeps only the host column.
  3. sort groups identical hosts together.
  4. uniq -c counts 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Processing Text with grep, sed, and awk and get answers drawn from it.

Signed-in readers only.