Skip to content

← 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>&1 sends stderr to wherever stdout currently points, &> is the short form for both.
  • Order matters: redirections are read left to right, so > file 2>&1 works and 2>&1 > file does not (you met this with tail -f in week 2).
  • Discarding: 2>/dev/null hides errors, and find / ... 2>/dev/null is the classic use.
  • Input: < file, here-strings (<<<) and here-documents (<<'EOF'). Quote the EOF marker to stop the shell from expanding $variables inside.
  • tee: copies the stream to a file and passes it on, so a pipeline can be inspected in the middle. tee -a appends.
  • Pitfall: sort file > file empties the file, because the shell truncates the target before sort runs. Use a temporary file or sort -o file file.
  • Pipeline status: $? is the status of the last command only. ${PIPESTATUS[@]} shows every stage, and set -o pipefail makes 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: -i ignore case, -n line numbers, -c count, -v invert, -w whole word, -l only file names, -o only the match.
  • -E for extended regular expressions (a|b, +, {2,3}), and -A, -B, -C for lines of context.
  • -r with --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: -d delimiter, -f fields, -c character positions. It only splits on one delimiter character, so runs of spaces confuse it (use awk for those).
  • wc: -l, -w, -c. wc -l < file prints the number only, without the file name.
  • sort:
  • -n numeric, -r reverse, -u unique, -h human sizes (10K, 2G).
  • -t, and -k4 sort by a field.
  • Without -n, 100 sorts before 9.
  • uniq: only collapses neighbouring duplicates, so sort first. -c counts, -d shows 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 the g flag, -n with p to print only selected lines, line addresses (2,4p), /pattern/d to delete.
  • -E for extended regular expressions with \1 back-references.
  • -i.bak edits in place and keeps a backup. Run it without -i first 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, NF is the count, NR the line number) and runs pattern { action }.
  • -F, sets the separator, and BEGIN and END blocks run before and after the input.
  • Associative arrays make "group by" easy: count[$2]++, then loop in END.
  • A field such as 187ms is treated as a number when used in arithmetic ($6+0).
  • awk is 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 -0 for file names with spaces. Compare with find ... -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:

  1. The top 10 error messages, counted.
  2. Requests per minute, busiest minutes first.
  3. The slowest endpoints, by average duration. Normalise the paths first (/api/items/7 and /api/items/12 are the same endpoint).
  4. Status code counts, and the share of requests that failed.
  5. 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 man and 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 nc or openssl s_client (14-16), finding an open port in a range with nmap (16), comparing files with diff (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>&1 and 2>&1 > file?
  • Can you tell why sort file > file destroys the file?
  • Can you count the most frequent value in a column of a log with one pipeline?
  • Can you explain why uniq needs sorted input?
  • Can you choose between cut, sed and awk for 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/' and awk '{print $1}' need single quotes, or the shell expands *, $1 and | before the tool sees them.
  • sed -i is destructive: run it without -i first, or use -i.bak.
  • xargs and spaces: plain xargs splits on spaces, so use -print0 | xargs -0 for file names.
  • Never test destructive commands on real data: xargs rm and sed -i belong in ~/tmp/pipes-lab while you learn.
  • Locale: sort follows the locale, so upper and lower case may sort together. Prefix LC_ALL=C when 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.