Parsing

Parsing Log Files With grep, awk and sed

By SweepLogs Editorial Team · · 4 min read

When something breaks on a server, you rarely have time to set up a full analysis platform. You have a terminal and a log file with millions of lines. Three classic Unix tools, grep, awk and sed, let you search, slice and reshape that text quickly, and they are available almost everywhere.

Each tool has a different strength. Grep finds lines, awk works with columns and calculations, and sed edits text as it flows past. Combined with sort and uniq, they cover a large part of everyday log analysis. The examples below use a web server access log in a common format, but the techniques apply to any line-based text.

A Sample Log

Imagine lines like this:

203.0.113.9 - - [27/Nov/2026:09:14:02 +0000] "GET /index.html HTTP/1.1" 200 5120
198.51.100.4 - - [27/Nov/2026:09:14:05 +0000] "POST /login HTTP/1.1" 401 312
203.0.113.9 - - [27/Nov/2026:09:14:09 +0000] "GET /missing HTTP/1.1" 404 210

Fields are separated by spaces: the client address first, the request in quotes, then the status code and the response size.

grep: Find the Lines You Want

The basic use is searching for a string:

grep "POST /login" access.log

Useful options include:

  • -i for case-insensitive matching.
  • -v to invert the match and show lines that do not contain the pattern.
  • -c to count matching lines instead of printing them.
  • -n to show line numbers.
  • -E for extended regular expressions, allowing alternation and repetition.
  • -A 3 and -B 3 to show lines after and before each match, for context.
  • -r to search recursively through a directory.

For example, to find server errors in the 500 range:

grep -E '" 5[0-9]{2} ' access.log

And to see an error with three lines of context on each side:

grep -C 3 "Out of memory" app.log

For compressed rotated logs, use zgrep, which searches gzip files directly without unpacking them first.

awk: Work With Columns

Awk splits each line into fields, named $(1), $(2) and so on, and lets you act on them. To print only the client address and status code:

awk '{print $(1), $(9)}' access.log

You can add conditions. This prints requests whose status is 404:

awk '$(9) == 404 {print $(1), $(7)}' access.log

Awk can calculate as it reads. This adds up the bytes sent:

awk '{sum += $(10)} END {print sum}' access.log

It also supports associative arrays, which are perfect for counting. This counts requests per status code:

awk '{count[$(9)]++} END {for (c in count) print c, count[c]}' access.log

If your fields are separated by something other than whitespace, use -F to set the separator, for example -F, for comma-separated data.

sed: Edit and Extract

Sed, the stream editor, is best known for substitution:

sed 's/password=[^ ]*/password=REDACTED/g' app.log

This is handy for removing secrets before sharing a log. Other common tasks:

  • Print a range of lines: sed -n '100,200p' app.log.
  • Print lines between two patterns: sed -n '/START/,/END/p' app.log.
  • Delete lines that match: sed '/healthcheck/d' access.log.

Add -i to edit a file in place, but be careful: it overwrites the original. Many people give it a suffix, such as -i.bak, to keep a backup copy.

Combine Tools With Pipes

The real power comes from chaining small tools. Each does one thing, and the pipe passes the result along. To find the ten most frequent client addresses:

awk '{print $(1)}' access.log | sort | uniq -c | sort -rn | head -10

Step by step: awk extracts the address, sort groups identical values, uniq -c counts them, sort -rn orders by count from highest to lowest, and head shows the top ten.

To find which pages return the most 404 errors:

grep '" 404 ' access.log | awk '{print $(7)}' | sort | uniq -c | sort -rn | head

To look at one time window, such as a particular minute:

grep "27/Nov/2026:09:14" access.log | awk '{print $(9)}' | sort | uniq -c

Note that uniq only collapses adjacent duplicates, so you must run sort before it.

Practical Tips

  • Test on a small sample first. Use head -1000 to try a command before running it on a huge file.
  • Quote your patterns. Single quotes stop the shell from changing special characters.
  • Mind the field numbers. Log formats differ, so print a few lines with fields numbered to confirm where values sit.
  • Handle quoted fields carefully. Spaces inside quotes break simple splitting. Use a different separator, such as the quote character, when needed.
  • Use fixed-string search for speed. grep -F skips regular expression processing and is faster for plain text.
  • Prefer structured logs. If your logs are JSON, a tool like jq is usually better than awk, since fields are named.
  • Watch the locale. Setting LC_ALL=C can speed up grep and sort on large ASCII files, though it changes how some characters are compared.

Know When to Move On

These tools shine for quick questions on one machine. If you need dashboards, long-term trends or searches across many servers, forward logs to a central system. Shell one-liners are for exploration, not a replacement for proper monitoring. Once a command becomes something you run daily, put it in a script with a comment explaining its purpose.

Frequently Asked Questions

When should I use grep, awk or sed?

Use grep to find lines that match, awk when you need to work with columns or compute totals, and sed to substitute or delete text. In practice you combine them. A common pattern is grep to narrow the data, awk to pick fields and sort with uniq to count.

Why is my uniq count wrong?

Uniq only merges adjacent identical lines, so unsorted input gives misleading counts. Always run sort before uniq, or use sort -u if you only need unique values without counts. Check that you are extracting the exact field you intend.

Are these commands different on macOS?

Mostly the same, but macOS ships BSD versions of some tools, and options such as sed -i and certain regular expression features differ from the GNU versions found on most Linux systems. Check the manual page on your system, or install the GNU versions if you need identical behavior.

Related reading