← Week 3 - Pipes and text tools | My notes | Exercises
Week 3 - Pipes and text tools: detailed plan¶
Goal: Use the shell as a data-processing tool.
Budget: 6-8 hours in 5 sessions. This file is the reference behind the weekly checklist. The drills to type are in week-03-exercises.md; your results and write-ups go in week-03-notes.md.
Reading: Ch. 6 Redirection; Ch. 7 Seeing the World as the Shell Sees It; Ch. 19 Regular Expressions (grep); Ch. 20 Text Processing (sort, uniq, cut, tr, sed). awk is not covered, use its man page.
Overview¶
| Session | Focus | Time | Exercise |
|---|---|---|---|
| 1 | Redirection, pipes, tee, here-strings |
1 h | 3 (part 1) |
| 2 | grep, tr, cut, wc, sort, uniq |
1.5 h | 1 (part 1) |
| 3 | sed, awk, xargs |
1.5 h | 1 (part 2) |
| 4 | Log analysis and process substitution | 1.5 h | 2 + 3 (part 2) |
| 5 (weekend) | Bandit 13-20, then one-liners and wrap-up | 2-3 h | 4 + deliverable |
All drills in sessions 1 to 4 work on one practice folder, ~/tmp/pipes-lab, which the setup script in the exercises builds. It holds a fake ASP.NET Core log (app.log, 600 lines), a small CSV, a text file and a few source files. Everything stays under ~, so there is nothing to clean up in /mnt/c.
Session 1: Redirection and pipes (Exercise 3, part 1)¶
Every command has three streams: stdin (0), stdout (1) and stderr (2). Redirection decides where each one goes; a pipe connects stdout of one command to stdin of the next.
- Output:
>overwrites,>>appends,2>redirects stderr only,2>&1sends stderr to wherever stdout currently points,&>is the short form for both. - Order matters: redirections are read left to right, so
> file 2>&1works and2>&1 > filedoes not (you met this withtail -fin week 2). - Discarding:
2>/dev/nullhides errors, andfind / ... 2>/dev/nullis the classic use. - Input:
< file, here-strings (<<<) and here-documents (<<'EOF'). Quote theEOFmarker to stop the shell from expanding$variablesinside. tee: copies the stream to a file and passes it on, so a pipeline can be inspected in the middle.tee -aappends.- Pitfall:
sort file > fileempties the file, because the shell truncates the target beforesortruns. Use a temporary file orsort -o file file. - Pipeline status:
$?is the status of the last command only.${PIPESTATUS[@]}shows every stage, andset -o pipefailmakes the whole pipeline fail when any stage fails.
Write down: one sentence on why 2>&1 > file and > file 2>&1 differ.
Session 2: Searching, cutting and counting (Exercise 1, part 1)¶
grep:- Options:
-iignore case,-nline numbers,-ccount,-vinvert,-wwhole word,-lonly file names,-oonly the match. -Efor extended regular expressions (a|b,+,{2,3}), and-A,-B,-Cfor lines of context.-rwith--include='*.cs'to search a tree.- Anchors
^and$. tr: translates or deletes single characters:tr a-z A-Z,tr -d 0-9,tr -s ' '(squeeze repeats). It reads stdin only.cut:-ddelimiter,-ffields,-ccharacter positions. It only splits on one delimiter character, so runs of spaces confuse it (useawkfor those).wc:-l,-w,-c.wc -l < fileprints the number only, without the file name.sort:-nnumeric,-rreverse,-uunique,-hhuman sizes (10K,2G).-t,and-k4sort by a field.- Without
-n,100sorts before9. uniq: only collapses neighbouring duplicates, so sort first.-ccounts,-dshows only duplicated lines.- The top-N pattern:
... | sort | uniq -c | sort -rn | head. You will use it again and again.
Write down: why uniq without sort can give wrong counts.
Session 3: sed, awk and xargs (Exercise 1, part 2)¶
sed:s/old/new/and thegflag,-nwithpto print only selected lines, line addresses (2,4p),/pattern/dto delete.-Efor extended regular expressions with\1back-references.-i.bakedits in place and keeps a backup. Run it without-ifirst to see the result.- Use
#as the delimiter when the pattern contains slashes:s#/api/#/v1/#. awk:- It reads a line, splits it into fields (
$1,$2,$NF,NFis the count,NRthe line number) and runspattern { action }. -F,sets the separator, andBEGINandENDblocks run before and after the input.- Associative arrays make "group by" easy:
count[$2]++, then loop inEND. - A field such as
187msis treated as a number when used in arithmetic ($6+0). awkis named after its authors (Aho, Weinberger, Kernighan), and it is a small language, not just a command.xargs: turns lines from stdin into arguments. Know-n 1,-I{}, and-print0 | xargs -0for file names with spaces. Compare withfind ... -exec cmd {} +, which does the same without a pipe.
Write down: when you would pick sed, when awk, and when cut for the same job.
Session 4: Log analysis and process substitution (Exercise 2 + Exercise 3, part 2)¶
Treat app.log like a real ASP.NET Core log and answer the questions with one pipeline each:
- The top 10 error messages, counted.
- Requests per minute, busiest minutes first.
- The slowest endpoints, by average duration. Normalise the paths first (
/api/items/7and/api/items/12are the same endpoint). - Status code counts, and the share of requests that failed.
- The 5 slowest single requests.
Then process substitution: <(command) makes the output of a command look like a file. Use it with diff, comm, paste and wc, and with while read ... done < <(command). Run the same counter once with cmd | while read ... and once with < <(cmd): the pipe version loses the variable, because each side of a pipe runs in a subshell.
If you have a real log from a .NET app (for example the one from week 2's tail-demo), run the same pipelines on it and compare.
Write down: the pipeline for each question and one thing that surprised you about the data.
Session 5: Bandit 13-20 and wrap-up (Exercise 4 + deliverable)¶
Bandit 13-20 shift from text tools to SSH and networking, with the pipe skills in supporting roles. Per bandit.md:
- Use the level template. Write the approach and the concept learned, but never passwords, keys or solutions.
- Try each level with
manand your own notes first. Time-box each level to 30 minutes before looking for hints. - Expect these themes: logging in with a private key (13), talking to a local port with
ncoropenssl s_client(14-16), finding an open port in a range withnmap(16), comparing files withdiff(17), running a command over SSH and shell startup files (18), and setuid binaries (19-20). - Remember the week 2 reminder: an SSH client refuses a private key whose mode is not
600. - Update the progress table in overthewire/README.md.
One-liners (deliverable): collect 15 useful one-liners, each with a one-line explanation, in the Pipes and text tools section of cheatsheet.md (and list them under Deliverable in the notes). Good candidates are the top-N pattern, requests per minute, sed path normalisation, the awk group-by, xargs -0, diff <(...) <(...) and tee in the middle of a pipeline. Only commands you have actually run.
Wrap-up:
- Tick the exercises and the Done box in week-03-pipes-and-text-tools.md.
- Set the status in week-03-notes.md to Done.
- Run the markdownlint check before pushing (see the README).
- Commit via a branch like
docs/week-03-..., matching the earlier weeks' PR flow.
Self-check before moving on¶
- Can you explain the difference between
> file 2>&1and2>&1 > file? - Can you tell why
sort file > filedestroys the file? - Can you count the most frequent value in a column of a log with one pipeline?
- Can you explain why
uniqneeds sorted input? - Can you choose between
cut,sedandawkfor a given job? - Can you pass file names with spaces safely through
xargs? - Can you say what
<(command)does and when you need it?
Risks and tips¶
- Quote patterns:
grep 'a|b',sed 's/x/y/'andawk '{print $1}'need single quotes, or the shell expands*,$1and|before the tool sees them. sed -iis destructive: run it without-ifirst, or use-i.bak.xargsand spaces: plainxargssplits on spaces, so use-print0 | xargs -0for file names.- Never test destructive commands on real data:
xargs rmandsed -ibelong in~/tmp/pipes-labwhile you learn. - Locale:
sortfollows the locale, so upper and lower case may sort together. PrefixLC_ALL=Cwhen you need byte order. - Bandit 13+ involves SSH keys and local network services, and the same rule holds: read the man pages carefully, that is the skill being trained.