Skip to main content

Processing Text in Linux with grep, awk, and sed

Filter, extract, and transform logs with grep, awk, sed, cut, sort, uniq, and jq. Build one-line pipelines that find the cause of an incident fast.

30 Terms

Overview and What You Will Learn

Linux text processing tools read lines from files or other commands, filter them, reshape them, and pass them on. grep finds lines, awk works with fields, sed rewrites text, cut, sort, and uniq handle columns and counting, and jq does the same for JSON. Chained with pipes, they turn a 500,000-line log into an answer in seconds.

By the end of this lab you will:

  • Filter logs with grep using fixed strings, regex, context, and counts
  • Extract fields, filter rows, and aggregate values with awk
  • Rewrite text and edit config files safely with sed
  • Cut columns, sort, deduplicate, and count with cut, sort, and uniq
  • Query and reshape JSON from APIs and logs with jq
  • Combine all of them into a reusable log analysis script

Why This Matters in Production

Every incident starts with reading logs, and every deployment script parses command output. An engineer who can chain these tools finds the top failing endpoint, the noisiest service, or the busiest client IP in one command instead of scrolling through a file.

On-call teams at companies such as Datadog and Cloudflare keep a small set of these pipelines in runbooks, because they work on any Linux host with no extra software and no ingestion delay.

Core Principles

Each tool does one job and reads standard input, so the output of one becomes the input of the next. Build a pipeline one stage at a time and check the output at every step.

flowchart TD A[(access.log
500,000 lines)] --> B[awk: keep
status 5xx] B --> C[awk: print
URL path] C --> D[sort then
uniq -c] D --> E[sort -rn
head -5] E --> F([Top failing URLs]) classDef src fill:#475569,color:#ffffff classDef filter fill:#326CE5,color:#ffffff classDef count fill:#8B5CF6,color:#ffffff classDef out fill:#10B981,color:#ffffff class A src class B,C filter class D,E count class F out

The labs use two sample formats. The nginx access log has the client IP in $1, the request path in $7, the status in $9, and the bytes sent in $10. The application log has a timestamp, service, level, and message:

TEXT
203.0.113.45 - - [15/Jan/2024:10:23:45 +0530] "GET /api/cart HTTP/1.1" 200 512
2024-01-15T10:23:45 payment-api ERROR Database connection failed
2024-01-15T10:23:46 cart-api INFO Order 8841 created
Tool Best for Reads
grep Finding lines that match Whole lines
awk Fields, conditions, totals Lines split into fields
sed Substituting and deleting text Lines as a stream
cut, sort, uniq Columns, ordering, counting Delimited lines
jq Querying and reshaping JSON JSON documents
Remember

grep '500' matches the number anywhere on the line, including bytes and URLs. To match a status code, test the status field: awk '$9 == 500', or awk '$9 ~ /^5/' for all 5xx.

Detailed Step-by-Step Practical Lab

Milestone 1: How to Filter Logs with grep
Bash
grep 'ERROR' /var/log/app/app.log
grep -i 'error' /var/log/app/app.log
grep -n 'ERROR' /var/log/app/app.log
grep -c 'ERROR' /var/log/app/app.log
# Lines that do NOT match
grep -v 'DEBUG' /var/log/app/app.log
# Context: 2 lines before and 3 after each match
grep -B 2 -A 3 'FATAL' /var/log/app/app.log
# Extended regex with alternation
grep -E 'ERROR|FATAL|CRITICAL' /var/log/app/app.log
# Fixed string, no regex (safest for text with dots, brackets, or user input)
grep -F 'payment-api[1234]' /var/log/app/app.log
# Print only the matching part
grep -oE 'user_id=[0-9]+' /var/log/app/app.log
# Which files contain a match
grep -l 'ERROR' /var/log/app/*.log
# Recursive search with file filters
grep -rn 'DATABASE_URL' /etc/ --include='*.conf'
# Whole word only
grep -w 'error' /var/log/app/app.log
# Rotated and compressed logs
zgrep 'ERROR' /var/log/app/app.log.*.gz
# Use the exit status in scripts
if grep -q 'FATAL' /var/log/app/app.log; then
echo "Fatal errors detected, alerting on-call"
fi

GNU grep -P supports Perl regex features such as lookbehind, for example grep -oP '(?<=user_id=)\d+'. It is not available in every grep, such as the one on macOS or in BusyBox, so prefer -oE where you can.

Milestone 2: How to Extract and Aggregate Fields with awk

awk splits each line into fields ($1, $2, ...) on whitespace, runs a pattern and action per line, and can keep totals in arrays.

Bash
# Print chosen fields (no need for cat)
awk '{print $1, $7, $9}' /var/log/nginx/access.log
# Custom field separator
awk -F: '{print $1, $3}' /etc/passwd
# Filter on a condition, skipping the header row
ps aux | awk 'NR > 1 && $3 > 10 {print $2, $11, $3"%"}'
# Count matches
awk '/ERROR/ {count++} END {print "Errors:", count+0}' /var/log/app/app.log
# Sum a column
awk '{sum += $10} END {printf "Total: %.2f MB\n", sum/1024/1024}' /var/log/nginx/access.log
# Group and count: requests per status code
awk '{codes[$9]++} END {for (c in codes) print c, codes[c]}' /var/log/nginx/access.log | sort -k2 -rn
# Only 5xx responses, then the paths that produced them
awk '$9 ~ /^5/ {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -5
# Pass shell values into awk safely with -v
awk -v svc="payment-api" '$2 == svc && $3 == "ERROR"' /var/log/app/app.log
# Errors per service from the application log
awk '$3 == "ERROR" {services[$2]++} END {for (s in services) print s, services[s]}' /var/log/app/app.log
# Filesystems over 70 percent full, with the header
df -h | awk 'NR == 1 || $5+0 > 70 {printf "%-20s %5s %5s\n", $6, $5, $4}'
# A line range with line numbers
awk 'NR >= 100 && NR <= 200 {print NR": "$0}' /var/log/app/app.log
Tip

grep PATTERN FILE | awk '{...}' is often one awk command: awk '/PATTERN/ {...}' FILE. Use whichever reads more clearly, and prefer awk once you also need fields or counts.

Milestone 3: How to Transform Text and Edit Files with sed

sed applies editing commands to each line. The most common one is s/old/new/, where the g flag replaces every match on the line.

Bash
# First match per line, then all matches
sed 's/localhost/postgres.mumbai-prod.devops.in/' config.yaml
sed 's/localhost/postgres.mumbai-prod.devops.in/g' config.yaml
# Delete comments, blank lines, or noisy lines
sed '/^#/d' config.yaml
sed '/^$/d' config.yaml
sed '/DEBUG/d' /var/log/app/app.log
# Print only a range between markers
sed -n '/BEGIN CERT/,/END CERT/p' certificate.pem
# Substitute only on lines that match a pattern
sed '/payment-api/s/8080/4000/' docker-compose.yaml
# Several edits at once
sed -e 's/localhost/10.0.2.100/g' -e 's/5432/5433/g' config.yaml
# A different delimiter when the pattern contains slashes
sed 's|/etc/nginx|/etc/nginx-prod|g' config.conf
# Insert before and append after a matching line
sed '/^\[Service\]/a User=payment-svc' myapp.service
sed '/^ExecStart=/a Restart=on-failure' myapp.service
# Strip trailing whitespace
sed 's/[[:space:]]*$//' file.txt

Preview first, then edit in place with a backup. Validate the result before reloading the service:

Bash
# 1. Preview the change
sed 's/^PasswordAuthentication yes/#&/' /etc/ssh/sshd_config | diff /etc/ssh/sshd_config -
# 2. Apply with a backup copy
sudo sed -i.bak 's/^PasswordAuthentication yes/#&/' /etc/ssh/sshd_config
# 3. Validate, then reload
sudo sshd -t && sudo systemctl reload ssh
Common Mistake

Running sed -i without previewing. One wrong expression can break a config file until you restore the backup. Run without -i first, use -i.bak, and validate with the service's own check command such as sshd -t or nginx -t.

Milestone 4: How to Use cut, sort, and uniq for Structured Data
Bash
# cut: pick columns by delimiter or character position
cut -d: -f1 /etc/passwd
cut -d: -f1,3 /etc/passwd
cut -d, -f2,4 report.csv
cut -c1-19 /var/log/app/app.log
# sort: text, numeric, reverse, by key, unique
sort /etc/hosts
sort -n numbers.txt
sort -rn numbers.txt
sort -t: -k3 -n /etc/passwd
sort -u ips.txt
# uniq only collapses ADJACENT duplicates, so sort first
sort ips.txt | uniq
sort ips.txt | uniq -c
sort ips.txt | uniq -d
# Frequency analysis: top 10 client IPs
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10
# Top error messages (message starts at field 4)
awk '$3 == "ERROR"' /var/log/app/app.log | cut -d' ' -f4- | sort | uniq -c | sort -rn | head -10
Remember

uniq removes only consecutive duplicate lines. For frequency analysis always use sort | uniq -c | sort -rn, so duplicates scattered through the file are counted together.

Milestone 5: How to Query JSON with jq

jq reads JSON and applies a filter. Use -r for raw text without quotes, and --arg to pass shell values in safely.

Bash
sudo apt install jq
# Pretty-print and extract fields
curl -fsS https://payments-api.mumbai-prod.devops.in/status | jq .
curl -fsS https://payments-api.mumbai-prod.devops.in/health | jq -r '.status'
curl -fsS https://payments-api.mumbai-prod.devops.in/metrics | jq '.services.payment.latency_ms'
# Arrays: first element, every element
curl -fsS https://payments-api.mumbai-prod.devops.in/servers | jq -r '.[0].hostname'
curl -fsS https://payments-api.mumbai-prod.devops.in/servers | jq -r '.[].hostname'
# Filter by condition
curl -fsS https://payments-api.mumbai-prod.devops.in/services | jq '.[] | select(.status == "down")'
# Pass a shell variable safely
REGION="ap-south-1"
curl -fsS https://payments-api.mumbai-prod.devops.in/services | jq --arg r "$REGION" '[.[] | select(.region == $r)]'
# Reshape into new objects, or into TSV and CSV
curl -fsS https://payments-api.mumbai-prod.devops.in/services | jq '[.[] | {name, status, uptime: .uptime_seconds}]'
curl -fsS https://payments-api.mumbai-prod.devops.in/services | jq -r '.[] | [.name, .status, .region] | @tsv'
# Count matches
curl -fsS https://payments-api.mumbai-prod.devops.in/services | jq '[.[] | select(.status == "down")] | length'
# Use jq as a test in scripts: exit code 1 if the filter is false or null
curl -fsS https://payments-api.mumbai-prod.devops.in/health | jq -e '.status == "healthy"' > /dev/null
# Docker and Kubernetes output
docker inspect payment-api | jq -r '.[0].State.Status'
kubectl get pods -o json | jq -r '.items[] | [.metadata.name, .status.phase] | @tsv'

Logs written as one JSON object per line can be filtered with jq directly. The fromjson? form skips lines that are not valid JSON instead of stopping:

Bash
jq -Rr 'fromjson? | select(.duration_ms > 1000) | "\(.duration_ms)ms \(.path)"' /var/log/app/app.jsonl \
| sort -rn | head -10
Milestone 6: How to Build a Reusable Log Analysis Script

This script assumes the application log format shown earlier. Under pipefail, a head that closes the pipe early can make upstream commands report a failure, so each section ends with || true.

Bash
#!/usr/bin/env bash
# analyse-logs.sh - summarise errors in an application log
# Usage: ./analyse-logs.sh [/var/log/app/app.log]
set -euo pipefail
LOG_FILE="${1:-/var/log/app/app.log}"
[[ -r "$LOG_FILE" ]] || { echo "cannot read $LOG_FILE" >&2; exit 1; }
echo "=== Log analysis: $LOG_FILE ==="
echo
echo "--- Totals ---"
echo "errors: $(grep -c ' ERROR ' "$LOG_FILE" || true)"
echo "fatal: $(grep -c ' FATAL ' "$LOG_FILE" || true)"
echo
echo "--- Top 5 error messages ---"
awk '$3 == "ERROR"' "$LOG_FILE" | cut -d' ' -f4- | sort | uniq -c | sort -rn | head -5 || true
echo
echo "--- Errors per minute (latest 10) ---"
awk '$3 == "ERROR" {print substr($1, 1, 16)}' "$LOG_FILE" | sort | uniq -c | tail -10 || true
echo
echo "--- Services with most errors ---"
awk '$3 == "ERROR" {print $2}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -5 || true

Production Best Practices & Common Pitfalls

Build pipelines incrementally, narrow the data early, and prefer tools that match the structure of the data.

  1. Filter as early as possible so later stages process fewer lines.
  2. Use grep -F or awk -v when the pattern or value comes from a variable or user input, so it is treated as data and not as code.
  3. Use jq for JSON, never grep or sed, because JSON can contain nested fields and escaped characters.
  4. Check each stage's output before adding the next one.
  5. Set LC_ALL=C for faster sort and grep on very large ASCII logs.
  6. Preview sed edits, keep backups, and validate configs before reloading.
Security

Never splice untrusted input into the text of an awk or sed program, because it can change what the program does. Pass values with awk -v name="$value", match literals with grep -F -- "$value", and use getent passwd USER for account lookups instead of parsing /etc/passwd.

Task Slower approach Better approach
Search one file cat log | grep ERROR grep ERROR log
Match a status code grep 500 log awk '$9 == 500' log
Count unique IPs Manual loop sort ips | uniq -c | sort -rn
Find big directories Browse manually du -xh --max-depth=1 / | sort -rh | head
Read a JSON field grep and cut jq -r '.field'

Quick Reference & Troubleshooting Commands

Task Command
Filter several levels grep -E 'ERROR|FATAL' app.log
Fixed-string search grep -F 'text' file
Extract a field awk '{print $3}' file
Custom delimiter awk -F: '{print $1}' /etc/passwd
Replace text sed 's/old/new/g' file
In-place edit with backup sed -i.bak 's/old/new/g' file
Frequency count sort file | uniq -c | sort -rn
JSON field jq -r '.field' response.json
Filter a JSON array jq '.[] | select(.status == "down")'
Symptom First command What to look for
Pattern finds nothing grep -c PATTERN file Wrong case, wrong field, hidden characters
awk prints wrong column awk '{print NF, $0}' file | head Field count differs from what you assumed
uniq -c shows many repeats sort file | uniq -c Input was not sorted first
sed changed too much sed 's/a/b/g' file | diff file - Pattern matching more than intended
jq reports a parse error jq . file Not valid JSON, or one object per line
Output has odd characters file logfile and cat -A | head Windows line endings or binary data
Tip

If a column looks wrong, run awk '{print NF}' file | sort | uniq -c. It shows how many fields each line has, which immediately reveals lines that do not match the format you expected.

Remember

grep works on lines, awk on fields, sed on text patterns, and jq on JSON structure. Choosing the tool that matches the structure of your data is what keeps pipelines short and correct.

Resources

Explore More in Linux Shell Scripting and Automation

All 6 Topics

Frequently Asked Questions

Is Processing Text in Linux with grep, awk, and sed free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Processing Text in Linux with grep, awk, and sed topic cover?

Filter, extract, and transform logs with grep, awk, sed, cut, sort, uniq, and jq. Build one-line pipelines that find the cause of an incident fast.

Found a mistake, an outdated step or a broken link?