Linux Command-Line Text Processing in Practice: Find with grep, Change with sed, Calculate with awk
A log file is not meant to be read line by line: count first, then search, then calculate. This guide works a fictional 20-line access log with grep, sed and awk: 5 ERROR lines, 4 WARN, 11 INFO; payments averages 350ms against orders 170ms and users 90ms, and the slowest single line is 400ms. GNU grep 3.11, GNU sed 4.9, mawk 1.3.4.

Your project has a problem. A user says checkout fails, you open the log file, and there are thousands of lines staring back at you. Where do you start? Reading the log line by line is not an option. The right approach is to count first, then search, then calculate: use grep to count how many lines are errors, sed to cover up sensitive information, and awk to work out which service is slowest. Those three tools are the whole kit for Linux command-line text processing: grep finds, sed changes, awk calculates. This guide practises on a fictional 20-line access log for three services, orders, users and payments. The demo script is demo245_zh.sh in the draft folder, the English rerun is rerun_en_demo245_g2.sh, and the numbers are identical in both runs. Local tool versions are GNU grep 3.11 and GNU sed 4.9, and awk here is mawk 1.3.4; the guide uses only POSIX-compatible syntax, which runs identically on GNU awk.
First, look at what a log line looks like. Every line in the demo log has the same shape: timestamp, level, service, method, endpoint, status code, latency, client IP. Line 4, for example, is 2026-11-24T09:00:04Z ERROR orders GET /api/orders 500 160ms 192.0.2.44, meaning that at 09:00:04 a GET request to the orders service returned a 500 and took 160 milliseconds. A fixed format is good news: when the format is fixed, the tools can work by position; when the format drifts, every command has to change with it. So the first step of text processing is always "look at a few lines of the raw data" before writing any command. Section 1 of the demo script does exactly that:
wc -l /tmp/demo245_text/app.log
What it does: it counts 20 lines in the log. Why count lines first: the line count is the denominator for every number that follows. Five ERROR lines out of 20 is a quarter of the log; five out of 20,000 would be a very different story. When debugging, report the total first and the breakdown second, so other people can judge the scale of the problem. Another habit: before doing anything, run head -n 5 logfile and read the first five lines to confirm the format matches what you assumed. What people say a log looks like and what it actually looks like are often different, and one look is the cheapest insurance.
Count levels with grep: first learn how much is broken
Section 2 of the demo script is the grep basics:
grep -c ERROR app.log
grep -c WARN app.log
grep -c INFO app.log
grep -c ' 500 ' app.log
grep -c ' 404 ' app.log
grep -c ' 429 ' app.log
grep -vc ' 200 ' app.log
grep -n ' 500 ' app.log
What it does: there are 5 ERROR lines, 4 WARN lines and 11 INFO lines, and the three add up to exactly 20, matching the total; status 500 appears 2 times, 404 appears 2 times, 429 appears 1 time; there are 5 non-200 lines; and the two lines with a 500 are lines 4 and 16. Why it is written this way: -c counts matching lines without printing them, so counting before reading is far faster; -v inverts the match, so grep -vc ' 200 ' counts the "not 200" lines, and its result of 5 agrees with 2 plus 2 plus 1 from the other direction, the two directions checking each other; -n prints line numbers, and lines 4 and 16 are the two lines worth reading in full. One detail: the spaces around the pattern are deliberate. Writing grep -c '500' without spaces would also match a 500 inside a timestamp or an IP address; writing ' 500 ' with spaces on both sides matches only the status-code position. Those "apparently extra" spaces are a habit that comes naturally once you have used grep for a while: the more precise the pattern, the more trustworthy the count.
Once you have counted the levels, the next question is "whose errors are these". A 500 is a server-side error, a 404 means not found, a 429 means too many requests, and the three are fixed in completely different ways: a 500 sends you to the server's code and logs, a 404 sends you to check the URL and the parameters, and a 429 means the other side is rate-limiting you, so you should stop and wait rather than retrying. The demo's 5 non-200 lines are spread across three services, so the next step is to group by service and see where the problem concentrates.
Group by service with grep: where does the problem concentrate
Section 3 of the demo script counts lines per service:
grep -c ' orders ' app.log
grep -c ' users ' app.log
grep -c ' payments ' app.log
What it does: the orders service has 8 lines, users has 6, payments has 6, and the three add up to 20 again. Why it is written this way: as in the previous section, the spaces around the service name keep the endpoint path /api/orders out of the count. This is a good place to mention a classic grep trap: -c counts lines, not occurrences. The word orders appears twice on a single line — once as the service name and once inside the path /api/orders — so grep -c 'orders' counts 1 line while grep -o 'orders' | wc -l counts 16 occurrences. In the measured run grep -c 'orders' gives 8 lines and grep -o 'orders' gives 16 matches, exactly double. Which to use when: if you want "how many lines have a problem", use -c; if you want "how many times does a word appear in total", use -o piped to wc -l. The two numbers being different is normal; the point is to know which one you are counting.
Three more grep options are worth knowing for debugging. -i ignores case: log levels are sometimes written Error and sometimes ERROR, and without -i you miss half of them. -E enables extended regular expressions, so one pattern can match several status codes: grep -cE ' (404|429|500) ' app.log also gives 5, agreeing with the 2 plus 2 plus 1 counted one by one. -A 2 -B 2 prints two lines after and two lines before each match, because an error is rarely a lone line — the lines around it are the context. And one locating trick: the first three lines of grep -n ERROR app.log are lines 4, 7 and 11, so with line numbers in hand you can jump straight to the original text instead of scrolling through thousands of lines.
Average latency with awk: which service is slowest
After counting "how much is broken", the next question is "how slow is it". Section 4 of the demo script is awk's home ground:
awk '{ gsub(/ms/, "", $7); sum[$3] += $7; n[$3]++ } END { print "orders average latency: " sum["orders"]/n["orders"] "ms"; print "users average latency: " sum["users"]/n["users"] "ms"; print "payments average latency: " sum["payments"]/n["payments"] "ms" }' app.log
awk '{ t = $7 + 0; if (t > max) { max = t; line = $0 } } END { print "Slowest line latency: " max "ms"; print "Slowest line: " line }' app.log
awk '{ print $5 }' app.log | sort | uniq -c | awk '{ print "Endpoint " $2 " appears " $1 " times" }'
What it does: the average latencies are orders 170 milliseconds, users 90 milliseconds and payments 350 milliseconds; the slowest single line is line 20 at 400 milliseconds, a POST request to the payments service; and the three endpoints appear 8, 6 and 6 times — /api/orders 8 times, /api/pay 6 times, /api/users 6 times. Why it is written this way: awk works by columns. $3 is the service name in column 3, $7 is the latency in column 7, sum[$3] += $7 adds up the latencies separately per service, n[$3]++ counts lines separately per service, and dividing the total by the count gives the average. The 8 orders lines took 100, 120, 140, 160, 180, 200, 220 and 240 milliseconds, adding up to 1360, divided by 8 is 170; the 6 users lines took 40, 60, 80, 100, 120 and 140, adding up to 540, divided by 6 is 90; the 6 payments lines took 300, 320, 340, 360, 380 and 400, adding up to 2100, divided by 6 is 350. Those three numbers are what the chart below draws: payments averages about twice orders and nearly four times users, so if performance needs work, payments is where to start.

There is a classic awk trap here, and the demo script walked straight into it at first, which makes it worth telling in full. Finding the slowest line, the first version was written as gsub(/ms/, "", $7); if ($7 > max), and the "slowest" line it found was 80 milliseconds, line 11 — even though a 400-millisecond line comes later. The reason is awk's comparison rule: once a field has been through gsub it is a string, and strings compare in dictionary order, where "400" starts with 4 and "80" starts with 8, so in dictionary order 4 is smaller than 8 and 400 milliseconds was judged "slower than" 80 milliseconds — or rather, smaller. The fix is to convert to a number before comparing: t = $7 + 0 turns "400ms" into the number 400 and the comparison works again. In the measured run the fixed answer is 400 milliseconds, line 20; checking the same numbers on their own, the string comparison gives 80 and the numeric comparison gives 400. The lesson: in awk, strip the unit off a column and convert it to a number before comparing or calculating. Averages do not need the same care, because addition automatically treats "100ms" as 100. The last pipeline is also worth learning: awk '{ print $5 }' takes the endpoint in column 5, and sort | uniq -c sorts and counts occurrences — the standard idiom for "how many of each value", used daily in log analysis and data cleaning.
Redact and replace with sed: back up before you change anything
Section 5 of the demo script is the sed basics:
sed -E 's/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[IP]/g' app.log | grep -c '\[IP\]'
sed -E 's/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[IP]/g' app.log | head -n 1
sed 's/ orders / order-service /g' app.log | grep -c 'order-service'
sed -n '4p' app.log
What it does: after replacing every IP address with [IP], all 20 lines contain [IP]; the first redacted line is 2026-11-24T09:00:01Z INFO orders GET /api/orders 200 100ms [IP]; renaming the service from orders to order-service changes 8 lines; and printing only line 4 gives 2026-11-24T09:00:04Z ERROR orders GET /api/orders 500 160ms 192.0.2.44. Why it is written this way: s/old/new/g is sed's substitute command, and the g means replace every occurrence on the line — without it only the first per line changes. [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ is the regular expression for an IP address, four groups of digits separated by dots, and the backslash before each dot tells sed "this dot is a literal dot, not any character". Redaction is sed's most common real-world job: before pasting a log into an issue or sending it to someone, cover up IP addresses, phone numbers and email addresses, then count with grep -c '\[IP\]' to confirm all 20 lines are covered before sending.
sed has one iron rule: back up before you change anything. None of the commands above uses -i, so they only print results and never touch the original file — the safest way to work while debugging. Once the replacement looks right, add -i.bak to edit for real, which keeps a .bak backup first. Writing sed -i with no backup means a wrong edit cannot be undone. One more easily missed detail: in sed -n '4p', -n means "do not print by default" and 4p means "print only line 4" — the two together print exactly one line. Without -n, sed prints the whole file and line 4 appears twice, which startles beginners with its doubled output. And a final reminder: the spaces around the service name in sed 's/ orders / order-service /g' matter just as they did in grep — without them, the orders inside the endpoint path gets renamed too.
One more step: context lines and counting by IP
Finding the failing line is only the start; the most useful information is often in the two lines around it. Line 4 of the demo log is a 500 error, and grep's context options show what surrounds it:
grep -n -B1 -A1 ' 500 ' app.log
What it does: line 4 comes with one line before and one after — line 3 is a WARN from the same service and line 5 is an INFO from the same service; line 16 is the same, with INFO lines on both sides. Why look at it this way: errors are rarely isolated. The WARN on line 3 may be the warning sign before the 500 on line 4, and the INFO on line 5 tells you whether the service recovered on its own afterwards. -B1 brings one line before, -A1 one line after, a dash before a line number marks a context line and a colon marks a match. The debugging order — count first, then look at lines, then look at context — saves a lot of wrong turns.
Another common question is "which client do the errors concentrate on". Take column 8, the IP, and count it:
awk '{ print $8 }' app.log | sort | uniq -c | sort -rn
What it does: the four IPs appear 6, 5, 5 and 4 times — 203.0.113.7 six times, 198.51.100.23 five times, 192.0.2.44 five times, 203.0.113.18 four times — and the four add up to 20, matching the total. Why it is written this way: sort | uniq -c is the standard idiom for "how many of each value", and the final sort -rn orders by count, most first. The number alone proves nothing — 203.0.113.7 appears 6 times only because it made the most requests, not because it is the source of the problem — but it tells you whom to check first. Combined with the previous section's pipeline, grep 'ERROR payments' app.log | awk '{ print $8 }' returns two IPs appearing once each, which suggests the payments service's two errors came from two different clients, so the problem is more likely on the server side than with one misbehaving client.
cut versus awk: two ways to take a column
Taking one column out does not need awk; cut can do it, and more simply:
cut -d' ' -f3 app.log | sort | uniq -c
What it does: it splits on spaces, takes column 3, the service name, and the counts are orders 8 times, payments 6 times, users 6 times, agreeing with the grep grouping. Why it is written this way: -d' ' sets the delimiter to a space and -f3 takes the third field. The division of labour between cut and awk is clear: whenever you take a column by a fixed delimiter, cut is shorter, faster and harder to get wrong; as soon as you need to filter by a condition, do arithmetic, or sum grouped by a column, you need awk. "Only compute the average latency for the payments service" cannot be done with cut, because cut cannot test whether column 3 is payments; awk does it with $3 == "payments". Remember the boundary: cut for taking columns, awk for calculating, and together the two answer most log questions right in the terminal.
Put it together: one pipeline answers one question
With the tools from the four sections above, here is a complete workflow. Suppose the question is "which IPs do the payments service's errors concentrate on":
grep 'ERROR payments' app.log | awk '{ print $8 }' | sort | uniq -c | sort -rn
What it does: grep first takes the payments service's ERROR lines, 2 lines in total; awk takes the IP in column 8; then sort, count, and order by count descending. In the measured run the two lines' IPs each appear once, one 192.0.2.44 and one 203.0.113.7. Why it is written this way: the pipeline's idea is "each step does exactly one thing". grep filters lines, awk takes a column, sort plus uniq -c counts, and the final sort -rn orders by count from most to fewest. When a step's result looks wrong, cut the pipeline off after that step and look — run grep 'ERROR payments' app.log alone first and confirm it returns 2 lines, then add the rest. This "add one segment at a time" way of debugging a pipeline is far faster than writing one long pipeline in a single breath and guessing where it broke. Two more numbers worth checking: grep -c '203\.0\.113' app.log gives 10 lines and grep -c '192\.0\.2\.44' app.log gives 5 lines, together 15 lines, and the remaining 5 lines belong to 198.51.100.23. The dots in an IP address must be written as \., because a dot in a regular expression means "any character", and without escaping, 203.0.113 would also match things like 203a0b113.
The five most common beginner mistakes
The first mistake is leaving the grep pattern unquoted: grep ERROR app.log looks fine, but once the pattern contains a space, a star or a bracket, the shell interprets it first and the error is baffling — always wrap patterns in single quotes. The second is confusing -c with -o: -c counts lines and -o counts occurrences, and in the demo orders is 8 lines but 16 occurrences, so decide which number you want before choosing. The third is comparing strings and numbers in awk: a column with a unit must be converted with + 0 before comparing, or 400 milliseconds will be judged smaller than 80 milliseconds, as the demo already proved. The fourth is running sed with -i straight onto the original file: without a .bak backup a wrong edit cannot be undone, so look at the result without -i first and only add it once the result is confirmed. The fifth is assuming a log's format never changes: after a service upgrade the column order moves, $7 in awk points at something else, and every statistic after it is wrong. So with every new log, read a few lines with head and count the columns before writing any command.
Debugging checklist: next time a log misbehaves, follow this order
Step one, count total lines with wc -l and read a few lines of raw data with head to confirm the format. Step two, count errors at each level with grep -c to learn the scale of the problem, then take line numbers with grep -n and read the worst few lines in full. Step three, group with grep -c by service and by status code to confirm where the problem concentrates. Step four, compute averages and maxima with awk to find the slowest service and the slowest single line, and check the numbers against the chart. Step five, redact with sed before sharing a log, and count to confirm every line is covered before sending. Once this flow is familiar, a log stops being "thousands of lines of hieroglyphs" and becomes five numbers: 20 lines in total, 5 ERROR lines, payments averaging 350 milliseconds, the slowest line 400 milliseconds, and the problem IPs appearing once each. With those five numbers in hand, an AI or a colleague can pick up the thread immediately.
Scope and next steps
One final safety reminder: before practising on a real log, copy it first and then work. The demo log has only 20 lines and can be regenerated if you break it; a real log may be the only record of a live service, and a sed -i cannot be undone. The right habit is cp app.log practice.log first, then practise grep, sed and awk on the copy, and only touch the original once you are confident. Redaction works the same way: run the redaction on the copy first, count to confirm every line is covered, and only then send the redacted version out. Command-line tools are powerful, and power means mistakes are costly too — "copy first, act second" matters more than ten extra options.
One more reminder is worth making: every example in this guide ran against a local fictional demo log, never against any real production log file. Practise on the demo log until the flow feels natural, and only then move to real logs — real logs carry user privacy and business data, so redact and back up before practising on them, and once grep, sed and awk feel natural on the demo log you will face a real log's surprises with far more confidence.
This guide covers only the basics of grep, sed and awk on logs: finding, changing and calculating. Not covered: writing Bash scripts, which cycle 244's "Bash Scripting from Scratch" guide covers; regular expressions in depth, which the same cycle's "Python Regex in Practice" guide covers; and log platforms, centralised logging and alerting systems, which are advanced topics best learned after this guide's flow is second nature. The suggested next step: take one of your own real logs, count its lines with wc -l, count its errors with grep -c ERROR, and compute one average latency with awk. After those three commands you already understand that log better than most people. One step further, put the three commands into a small check script and run it first thing every working day — the health of your services becomes visible at a glance. Text-processing skill is not memorised; it is practised by walking the checklist every time something breaks.
Comments (0)
Sources
Related articles
Building stock of 2000 books moves current memory from 0.3 KiB to 582.7 KiB; subtracting two snapshots, the biggest line is line 85 at 568.1 KiB and 9699 blocks; getsizeof sees only 15.8 KiB, and clearing brings the line back to 0.0 KiB. Python 3.12.3 stdlib, measured.
tmux 3.4, zero packages: 1 session, 2 windows, 3 panes; the logs window prints 1 to 5, editor panes report ready. Detach with Ctrl-b d, reattach with tmux attach — the session outlives the connection. Mouse, prefix key and history limit in ~/.tmux.conf included.
GCC 13.3.0, C17, zero packages: a first C program, sizeof results 1/2/4/8/8/4/8/8, sum 1..100 is 5050, 10! is 3628800, 8 numbers sorted, 3 books total 1088 pages, 3 file lines and 70 chars read back. Preprocessing alone expands 3 lines to 815.