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
grepusing 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, anduniq - 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.
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:
203.0.113.45 - - [15/Jan/2024:10:23:45 +0530] "GET /api/cart HTTP/1.1" 200 5122024-01-15T10:23:45 payment-api ERROR Database connection failed2024-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', orawk '$9 ~ /^5/'for all 5xx.
Detailed Step-by-Step Practical Lab
Milestone 1: How to Filter Logs with grep
grep 'ERROR' /var/log/app/app.loggrep -i 'error' /var/log/app/app.loggrep -n 'ERROR' /var/log/app/app.loggrep -c 'ERROR' /var/log/app/app.log # Lines that do NOT matchgrep -v 'DEBUG' /var/log/app/app.log # Context: 2 lines before and 3 after each matchgrep -B 2 -A 3 'FATAL' /var/log/app/app.log # Extended regex with alternationgrep -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 partgrep -oE 'user_id=[0-9]+' /var/log/app/app.log # Which files contain a matchgrep -l 'ERROR' /var/log/app/*.log # Recursive search with file filtersgrep -rn 'DATABASE_URL' /etc/ --include='*.conf' # Whole word onlygrep -w 'error' /var/log/app/app.log # Rotated and compressed logszgrep 'ERROR' /var/log/app/app.log.*.gz # Use the exit status in scriptsif grep -q 'FATAL' /var/log/app/app.log; then echo "Fatal errors detected, alerting on-call"fiGNU 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.
# Print chosen fields (no need for cat)awk '{print $1, $7, $9}' /var/log/nginx/access.log # Custom field separatorawk -F: '{print $1, $3}' /etc/passwd # Filter on a condition, skipping the header rowps aux | awk 'NR > 1 && $3 > 10 {print $2, $11, $3"%"}' # Count matchesawk '/ERROR/ {count++} END {print "Errors:", count+0}' /var/log/app/app.log # Sum a columnawk '{sum += $10} END {printf "Total: %.2f MB\n", sum/1024/1024}' /var/log/nginx/access.log # Group and count: requests per status codeawk '{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 themawk '$9 ~ /^5/ {print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -5 # Pass shell values into awk safely with -vawk -v svc="payment-api" '$2 == svc && $3 == "ERROR"' /var/log/app/app.log # Errors per service from the application logawk '$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 headerdf -h | awk 'NR == 1 || $5+0 > 70 {printf "%-20s %5s %5s\n", $6, $5, $4}' # A line range with line numbersawk 'NR >= 100 && NR <= 200 {print NR": "$0}' /var/log/app/app.logTip
grep PATTERN FILE | awk '{...}'is often oneawkcommand:awk '/PATTERN/ {...}' FILE. Use whichever reads more clearly, and preferawkonce 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.
# First match per line, then all matchessed 's/localhost/postgres.mumbai-prod.devops.in/' config.yamlsed 's/localhost/postgres.mumbai-prod.devops.in/g' config.yaml # Delete comments, blank lines, or noisy linessed '/^#/d' config.yamlsed '/^$/d' config.yamlsed '/DEBUG/d' /var/log/app/app.log # Print only a range between markerssed -n '/BEGIN CERT/,/END CERT/p' certificate.pem # Substitute only on lines that match a patternsed '/payment-api/s/8080/4000/' docker-compose.yaml # Several edits at oncesed -e 's/localhost/10.0.2.100/g' -e 's/5432/5433/g' config.yaml # A different delimiter when the pattern contains slashessed 's|/etc/nginx|/etc/nginx-prod|g' config.conf # Insert before and append after a matching linesed '/^\[Service\]/a User=payment-svc' myapp.servicesed '/^ExecStart=/a Restart=on-failure' myapp.service # Strip trailing whitespacesed 's/[[:space:]]*$//' file.txtPreview first, then edit in place with a backup. Validate the result before reloading the service:
# 1. Preview the changesed 's/^PasswordAuthentication yes/#&/' /etc/ssh/sshd_config | diff /etc/ssh/sshd_config - # 2. Apply with a backup copysudo sed -i.bak 's/^PasswordAuthentication yes/#&/' /etc/ssh/sshd_config # 3. Validate, then reloadsudo sshd -t && sudo systemctl reload sshCommon MistakeRunning
sed -iwithout previewing. One wrong expression can break a config file until you restore the backup. Run without-ifirst, use-i.bak, and validate with the service's own check command such assshd -tornginx -t.
Milestone 4: How to Use cut, sort, and uniq for Structured Data
# cut: pick columns by delimiter or character positioncut -d: -f1 /etc/passwdcut -d: -f1,3 /etc/passwdcut -d, -f2,4 report.csvcut -c1-19 /var/log/app/app.log # sort: text, numeric, reverse, by key, uniquesort /etc/hostssort -n numbers.txtsort -rn numbers.txtsort -t: -k3 -n /etc/passwdsort -u ips.txt # uniq only collapses ADJACENT duplicates, so sort firstsort ips.txt | uniqsort ips.txt | uniq -csort ips.txt | uniq -d # Frequency analysis: top 10 client IPsawk '{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 -10Remember
uniqremoves only consecutive duplicate lines. For frequency analysis always usesort | 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.
sudo apt install jq # Pretty-print and extract fieldscurl -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 elementcurl -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 conditioncurl -fsS https://payments-api.mumbai-prod.devops.in/services | jq '.[] | select(.status == "down")' # Pass a shell variable safelyREGION="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 CSVcurl -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 matchescurl -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 nullcurl -fsS https://payments-api.mumbai-prod.devops.in/health | jq -e '.status == "healthy"' > /dev/null # Docker and Kubernetes outputdocker 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:
jq -Rr 'fromjson? | select(.duration_ms > 1000) | "\(.duration_ms)ms \(.path)"' /var/log/app/app.jsonl \ | sort -rn | head -10Milestone 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.
# 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 ===" echoecho "--- Totals ---"echo "errors: $(grep -c ' ERROR ' "$LOG_FILE" || true)"echo "fatal: $(grep -c ' FATAL ' "$LOG_FILE" || true)" echoecho "--- Top 5 error messages ---"awk '$3 == "ERROR"' "$LOG_FILE" | cut -d' ' -f4- | sort | uniq -c | sort -rn | head -5 || true echoecho "--- Errors per minute (latest 10) ---"awk '$3 == "ERROR" {print substr($1, 1, 16)}' "$LOG_FILE" | sort | uniq -c | tail -10 || true echoecho "--- Services with most errors ---"awk '$3 == "ERROR" {print $2}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -5 || trueProduction Best Practices & Common Pitfalls
Build pipelines incrementally, narrow the data early, and prefer tools that match the structure of the data.
- Filter as early as possible so later stages process fewer lines.
- Use
grep -Forawk -vwhen the pattern or value comes from a variable or user input, so it is treated as data and not as code. - Use
jqfor JSON, nevergreporsed, because JSON can contain nested fields and escaped characters. - Check each stage's output before adding the next one.
- Set
LC_ALL=Cfor fastersortandgrepon very large ASCII logs. - Preview
sededits, keep backups, and validate configs before reloading.
SecurityNever splice untrusted input into the text of an
awkorsedprogram, because it can change what the program does. Pass values withawk -v name="$value", match literals withgrep -F -- "$value", and usegetent passwd USERfor 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 |
TipIf 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
grepworks on lines,awkon fields,sedon text patterns, andjqon JSON structure. Choosing the tool that matches the structure of your data is what keeps pipelines short and correct.