← Week 3 - Pipes and text tools | Plan | My notes
Week 03 - Exercises¶
Try each task yourself first; the solutions are at the end of this file. Parts A to H use one practice folder, so you can drill the commands without touching real data. The parts follow the sessions in the plan:
| Part | Topic | Plan exercise |
|---|---|---|
| A | Redirection and pipes | 3 |
| B | grep, tr, cut, wc |
1 |
| C | sort and uniq |
1 |
| D | sed |
1 |
| E | awk |
1 |
| F | xargs |
1 |
| G | Log analysis | 2 |
| H | Process substitution | 3 |
Setup: the practice folder¶
Run this once. It builds ~/tmp/pipes-lab with a fake ASP.NET Core request log, a small CSV, a text file and a few source files. Because the random numbers are seeded, you get the same app.log every time with this script in bash: 600 lines, of which 458 are INFO, 69 are WARN and 73 are ERROR. Use those totals to check that the setup worked.
rm -rf ~/tmp/pipes-lab && mkdir -p ~/tmp/pipes-lab/src/App ~/tmp/pipes-lab/src/Lib && cd ~/tmp/pipes-lab
# 1. A fake request log, one line per request, sorted by time:
# <time> <level> <method> <path> <status> <duration> [message]
RANDOM=42
errs=("NullReferenceException in OrderService" "Timeout calling payment gateway" "SqlException: deadlock victim" "Unhandled exception in UserController")
for i in $(seq 1 600); do
m=$((RANDOM % 60)); s=$((RANDOM % 60))
case $((RANDOM % 5)) in
0) p=/api/items/$((RANDOM % 20)) ;;
1) p=/api/orders/$((RANDOM % 20)) ;;
2) p=/api/users/$((RANDOM % 20)) ;;
3) p=/health ;;
4) p=/weatherforecast ;;
esac
r=$((RANDOM % 100))
if [ $r -lt 75 ]; then lvl=INFO; st=200; ms=$((RANDOM % 200 + 5)); msg=""
elif [ $r -lt 88 ]; then lvl=WARN; st=404; ms=$((RANDOM % 200 + 5)); msg="Not found"
else lvl=ERROR; st=500; ms=$((RANDOM % 1500 + 100)); msg="${errs[$((RANDOM % 4))]}"
fi
printf '2026-12-01T10:%02d:%02d %s GET %s %d %dms %s\n' $m $s $lvl $p $st $ms "$msg"
done > raw.log
sort raw.log | sed 's/ $//' > app.log && rm raw.log
# 2. A small CSV
cat > people.csv <<'EOF'
name,team,city,salary
Anna,dev,Berlin,5200
Ben,ops,Hamburg,4800
Carla,dev,Munich,5600
David,qa,Berlin,4300
Eva,ops,Berlin,5000
Felix,dev,Hamburg,5900
Greta,qa,Munich,4500
EOF
# 3. A small text file
cat > notes.txt <<'EOF'
Linux is fun
linux is everywhere
TODO: learn awk
todo: learn sed
Pipes connect commands
The quick brown fox
the end
EOF
# 4. A few source files
printf '// TODO: add logging\nclass Program {}\n' > src/App/Program.cs
printf '// TODO fix\n// FIXME later\nclass Util {}\n' > src/Lib/Util.cs
printf 'TODO docs\n' > src/Lib/Readme.md
Check it: wc -l app.log prints 600 app.log, and head -3 app.log shows lines like this:
2026-12-01T10:00:04 ERROR GET /api/users/7 500 1390ms SqlException: deadlock victim
2026-12-01T10:00:34 INFO GET /api/orders/11 200 104ms
2026-12-01T10:00:37 INFO GET /api/orders/14 200 44ms
Work from inside the folder (cd ~/tmp/pipes-lab) for every part.
Part A: redirection and pipes¶
- A1. Write the output of
datetoout.txt, then append the output ofhostname. Show the file.
date > out.txt
hostname >> out.txt
cat out.txt
- A2. Run
ls /nonexistentand send only the error message toerr.txt. Check that nothing appeared on the screen.
ls /nonexistent 2> err.txt
cat err.txt
- A3. Run
ls /nonexistent /tmpso that stdout goes toout.txtand stderr goes toerr.txt, in one command. What is in each file?
ls /nonexistent /tmp > out.txt 2> err.txt
cat out.txt
cat err.txt
- A4. Send both streams of the same command to one file, once with
2>&1and once with&>.
ls /nonexistent /tmp > combined.txt 2>&1
cat combined.txt
ls /nonexistent /tmp &> combined.txt
cat combined.txt
- A5. Count the
.conffiles under/etcwithout the permission-denied noise.
find /etc -type f -name '*.conf' 2>/dev/null | wc -l
# explanation:
# 1. find /etc -name '*.conf' searches /etc recursively for names ending
# in .conf. If you only want regular files, and not directories or symlinks that happen to end in .conf, add -type f:
# 2. 2>/dev/null sends stderr to /dev/null. The "Permission denied" messages go to stderr, so this removes them and leaves stdout alone.
# 3. | wc -l counts the lines on stdout, which is one per match.
- A6. Run
ls /usr/bin | tee bins.txt | wc -l. How many lines went intobins.txt? Then usetee -ato add a line to it.
# Count the number of lines in /usr/bin and save the output to bins.txt
ls /usr/bin | tee bins.txt | wc -l # 1037
wc -l bins.txt # 1037
# Append a line to bins.txt using tee -a
echo "my extra line" | tee -a bins.txt
wc -l bins.txt # 1038
NOTE: what is the difference between tee and >?
The > operator is used for output redirection in the shell. It takes the output of a command and writes it to a file, overwriting the file if it already exists. For example, ls > file.txt will write the output of the ls command to file.txt, replacing any existing content in that file.
The tee command, on the other hand, is used to read from standard input and write to both standard output and one or more files simultaneously. It allows you to see the output of a command on the terminal while also saving it to a file. For example, ls | tee file.txt will display the output of ls on the terminal and also write it to file.txt. If you use tee -a file.txt, it will append the output to the file instead of overwriting it.
- A7. Count the words in the text
one two threewith a here-string.
wc -w <<< "one two three" # 3
- A8. Compare
wc -l app.logwithwc -l < app.log. What differs, and why?
wc -l app.log
# wc gets the filename as an argument. It opens the file itself, so it knows the name and prints it after the count.
wc -l < app.log
# The shell opens app.log and connects it to wc's standard input before wc starts. wc never sees a filename. It just reads an anonymous stream, so it prints only the number.
- A9. Copy
notes.txtton2.txt, then runsort n2.txt > n2.txt. What is inn2.txtafterwards, and why? How do you sort a file in place safely? - A10. Run
ls /nonexistent | wc -l; echo $?, then look at${PIPESTATUS[@]}. Why is$?zero? What doesset -o pipefailchange?
Part B: grep, tr, cut, wc¶
- B1. Show the lines of
notes.txtthat containlinux, ignoring case. - B2. Show the matching lines of
todo(any case) with their line numbers. - B3. Count the lines of
notes.txtthat do not containtodo(any case). - B4. Find the whole word
theinnotes.txt. Which line matches, and why notThe? - B5. Search
srcrecursively forTODOand show file name and line number. - B6. Repeat B5 for
.csfiles only, then list only the names of the files that containTODO. - B7. Count the lines in
srcthat containTODOorFIXME, any case (-E). - B8. Extract only the status codes (
404and500) fromapp.logwith-o, and count how often each appears. - B9. Show the first
ERRORline with one line of context before and after it. - B10. Count the requests that happened in the last ten minutes of the hour (times
10:50to10:59) using an anchor. - B11. Turn
hello worldinto upper case withtr. Then delete all digits froma1b2c3, and squeezea b cinto single spaces. - B12. Print the first and third column of
people.csvwithcut. Then print the log level (the second space-separated field) of the first two lines ofapp.log. - B13. Show the line, word and byte counts of
notes.txtin one command. - B14. Make a mixed file with
{ head -c 64 /dev/urandom; printf '\n==== secret42\n'; head -c 64 /dev/urandom; } > mixed.bin. Show only the human-readable strings of it withstrings, then keep only the line with two or more=characters. - B15. From the line
==== secret42, print only the text after the=characters, once withgrep -oPand\K, once withsed. - B16. Encode the text
hello linuxwithbase64and save it inencoded.txt. Then decode the file again withbase64 -d. - B17. Decode the base64 text
SGVsbG8gTGludXg=without creating a file, usingechoand a pipe. Why doesecho -nmatter when you encode? - B18. With
tr, rotate every letter ofHello Linuxby 13 positions (ROT13), keeping the case. Then run the result through the same command again. What do you get, and why?
Part C: sort and uniq¶
- C1. Sort
notes.txtalphabetically. Which lines come first, and where do the lines starting with a lower case letter go? - C2. Sort the numbers
10,9and100with a plainsort, then withsort -n. Why do they differ? - C3. Skip the header of
people.csvand show the best-paid person by sorting on the fourth field. - C4. From the lines
a,b,a(useprintf), show unique lines withsort -u, then count them withsort | uniq -c, and show only the duplicated one withuniq -d. - C5. Run
uniqon the same input without sorting first. What changes? - C6. Count how many log lines there are per level (
INFO,WARN,ERROR), most frequent first. - C7. Sort the sizes
1K,1Gand1Mfrom largest to smallest withsort -h. - C8. From the lines
a,b,a,c(useprintf), show only the lines that occur exactly once. Why is thesortneeded beforeuniq -u?
Part D: sed¶
- D1. Replace
linuxwithLinuxin the second line ofnotes.txtand print the result (do not change the file). - D2. Replace every
owith0in the first line (thegflag). - D3. Print only lines 2 to 4 of
notes.txt. - D4. Show
notes.txtwithout the lines that containTODO. Istodoremoved too? - D5. Copy
notes.txtton3.txt. Replacefunwithgreatin place, keeping a backup, and usediffto see the change. - D6. In
app.log, put a space between each duration number andms(187msbecomes187 ms) using-Eand a back-reference. Show the first line. - D7. Normalise the endpoints so
/api/items/7and/api/items/12both become/api/items/ID(also forordersandusers), then count the requests per endpoint. - D8. Print only the
ERRORlines of the log withsed -n.
Part E: awk¶
- E1. Count the log lines per level with
awkanduniq -c. - E2. Print the name and salary of the first two people in
people.csv, without the header. - E3. Add up the salaries and print the total and the average.
- E4. Count the people per team with an associative array.
- E5. Sum the salaries per team.
- E6. Print the log lines with a duration over 1500 ms. Why does
$6+0 > 1500work although$6looks like1585ms? - E7. Count the
ERRORlines that took longer than 1000 ms. - E8. Print
startbefore and<N> linesafter the input, usingBEGINandEND. What isNRin theENDblock? - E9. Show how many log lines have each number of fields (
NF). Why do they differ?
Part F: xargs¶
- F1. Count the lines of all
.csfiles undersrcwithfind | xargs wc -l. - F2. Print the words
a b cone per line withxargs -n 1. - F3. Run
echo file:{}for every.csfile withxargs -I{}. - F4. Create a file named
my file.txt. Show thatfind . -name 'my*' | xargs lsfails, then fix it with-print0and-0. Remove the file again. - F5. Do the same job as F1 with
find ... -exec wc -l {} +. When would you still preferxargs?
Part G: log analysis¶
- G1. The top 10 error messages: the text after the duration on
ERRORlines, with counts, most frequent first. - G2. Requests per minute: the three busiest minutes.
- G3. The slowest endpoints: normalise the paths, then show the three with the highest average duration (in ms).
- G4. Count the requests per status code.
- G5. The share of requests that were errors, as a percentage with one decimal.
- G6. The five slowest single requests (time, level, path, duration).
- G7. The three busiest minutes for
ERRORlines only. - G8. Build one command that prints a summary: total lines, errors, warnings and the slowest duration. Use
awkonly.
Part H: process substitution¶
- H1. Use
diff <(...) <(...)to compare the sorted names ofpeople.csv(without header) with the sorted lines ofnotes.txt. Why can you not use|here? - H2. Count the
ERRORlines withwc -l <(grep ERROR app.log). What name doeswcprint, and why? - H3. Use
comm -12with two process substitutions to list the API areas (/api/items, ...) that appear in both the log and the list/api/itemsand/api/zzz. - H4. Count the
ERRORlines with a counter in awhile readloop fed by a pipe. Print the counter after the loop. Is it right? - H5. Repeat H4, feeding the loop with
< <(grep ERROR app.log). Explain the difference. - H6. Print the level and the duration side by side with
paste <(...) <(...)for the first three lines.
Solutions¶
Peek only after you tried. Run everything from ~/tmp/pipes-lab.
cd ~/tmp/pipes-lab
# Part A
date > out.txt; hostname >> out.txt; cat out.txt # A1: > overwrites, >> appends
ls /nonexistent 2> err.txt # A2: only stdout would show; nothing appears
ls /nonexistent /tmp > out.txt 2> err.txt # A3: out.txt has the /tmp listing, err.txt the error
ls /nonexistent /tmp > all.txt 2>&1 # A4: both streams in one file
ls /nonexistent /tmp &> all2.txt # A4: the short form
find /etc -name '*.conf' 2>/dev/null | wc -l # A5
ls /usr/bin | tee bins.txt | wc -l # A6: bins.txt gets the same lines wc counts
echo "extra" | tee -a bins.txt > /dev/null # A6: -a appends
wc -w <<< "one two three" # A7: prints 3
cat <<'EOF' > hello.txt
Hello $HOME
EOF
cat hello.txt # A7: quoted EOF, so $HOME stays literal
wc -l app.log; wc -l < app.log # A8: the first prints "600 app.log", the second only "600":
# with < the shell opens the file, so wc does not know its name
cp notes.txt n2.txt; sort n2.txt > n2.txt; wc -c < n2.txt # A9: 0 bytes. The shell truncates n2.txt before sort reads it.
sort -o n2.txt n2.txt # A9: safe, or use a temporary file
ls /nonexistent | wc -l; echo $? # A10: $? is the status of the last stage only (wc: 0)
ls /nonexistent | wc -l; echo "${PIPESTATUS[@]}" # A10: 2 0, one status per stage
set -o pipefail # A10: now the whole pipeline fails if any stage fails
# Part B
grep -i linux notes.txt # B1
grep -in todo notes.txt # B2
grep -vic todo notes.txt # B3: 5 (-c counts, -v inverts, -i ignores case)
grep -w the notes.txt # B4: only "the end": matching is case sensitive without -i
grep -rn TODO src # B5
grep -rn --include='*.cs' TODO src # B6
grep -rl TODO src # B6: -l prints only file names
grep -riE 'todo|fixme' src | wc -l # B7: 4
grep -oE ' [45][0-9]{2} ' app.log | sort | uniq -c # B8: 69 for 404, 73 for 500
grep -B1 -A1 -m1 ERROR app.log # B9: -m1 stops after the first match
grep -c '^2026-12-01T10:5' app.log # B10: ^ anchors at the start of the line
echo "hello world" | tr a-z A-Z # B11
echo "a1b2c3" | tr -d 0-9
echo "a b c" | tr -s ' '
cut -d, -f1,3 people.csv # B12
cut -d' ' -f2 app.log | head -2
wc notes.txt # B13: lines, words, bytes (7 21 116)
{ head -c 64 /dev/urandom; printf '\n==== secret42\n'; head -c 64 /dev/urandom; } > mixed.bin
strings mixed.bin | grep -E '={2,}' # B14: strings drops the binary noise, grep keeps the line with ==
echo '==== secret42' | grep -oP '={2,}\s*\K\S+' # B15: \K discards everything matched so far, so only secret42 is printed
echo '==== secret42' | sed -E 's/^=+ *//' # B15: or strip the leading = and spaces with sed
echo 'hello linux' | base64 > encoded.txt # B16: aGVsbG8gbGludXgK
base64 -d encoded.txt # B16: hello linux
echo 'SGVsbG8gTGludXg=' | base64 -d; echo # B17: Hello Linux (the file's trailing newline is part of the data, so it is part of the encoding)
echo -n 'hello linux' | base64 # B17: aGVsbG8gbGludXg= (without -n, echo adds a newline that changes the encoded output)
echo 'Hello Linux' | tr 'A-Za-z' 'N-ZA-Mn-za-m' # B18: Uryyb Yvahk
echo 'Uryyb Yvahk' | tr 'A-Za-z' 'N-ZA-Mn-za-m' # B18: Hello Linux (the alphabet has 26 letters, so rotating by 13 twice returns the original)
# Part C
sort notes.txt # C1: depends on the locale: with LC_ALL=C all upper case comes first, in en_US.UTF-8 they are mixed
printf '10\n9\n100\n' | sort # C2: 10, 100, 9 (text order)
printf '10\n9\n100\n' | sort -n # C2: 9, 10, 100 (numeric)
tail -n +2 people.csv | sort -t, -k4 -n | tail -1 # C3: Felix,dev,Hamburg,5900
printf 'a\nb\na\n' | sort -u # C4: a, b
printf 'a\nb\na\n' | sort | uniq -c # C4: 2 a, 1 b
printf 'a\nb\na\n' | sort | uniq -d # C4: a
printf 'a\nb\na\n' | uniq # C5: nothing is collapsed, because the two a are not neighbours
cut -d' ' -f2 app.log | sort | uniq -c | sort -rn # C6: 458 INFO, 73 ERROR, 69 WARN
printf '1K\n1M\n1G\n' | sort -hr # C7: 1G, 1M, 1K
printf 'a\nb\na\nc\n' | sort | uniq -u # C8: b, c (-u keeps only lines that occur once; sort puts duplicates next to each other, uniq only compares neighbours)
# Part D
sed -n '2s/linux/Linux/p' notes.txt # D1: or: sed 's/linux/Linux/' notes.txt | sed -n 2p
sed '1s/o/0/g' notes.txt | head -1 # D2: without g only the first o per line changes
sed -n '2,4p' notes.txt # D3
sed '/TODO/d' notes.txt # D4: "todo: learn sed" stays: case sensitive
cp notes.txt n3.txt; sed -i.bak 's/fun/great/' n3.txt # D5
diff n3.txt n3.txt.bak
sed -E 's/([0-9]+)ms/\1 ms/' app.log | head -1 # D6
sed -E 's#/(items|orders|users)/[0-9]+#/\1/ID#' app.log | cut -d' ' -f4 | sort | uniq -c # D7
sed -n '/ERROR/p' app.log # D8
# Part E
awk '{print $2}' app.log | sort | uniq -c # E1
awk -F, 'NR>1 {print $1, $4}' people.csv | head -2 # E2: NR>1 skips the header
awk -F, 'NR>1 {sum+=$4} END {print sum, sum/(NR-1)}' people.csv # E3: 35300 5042.86
awk -F, 'NR>1 {c[$2]++} END {for (t in c) print t, c[t]}' people.csv | sort # E4
awk -F, 'NR>1 {s[$2]+=$4} END {for (t in s) printf "%s %.0f\n", t, s[t]}' people.csv | sort # E5
awk '$6+0 > 1500' app.log # E6: awk reads the leading number of "1585ms" when you add 0
awk '$2=="ERROR" && $6+0 > 1000 {n++} END {print n}' app.log # E7
awk 'BEGIN {print "start"} END {print NR " lines"}' app.log # E8: NR holds the last line number, 600
awk '{print NF}' app.log | sort -n | uniq -c # E9: 458 lines with 6 fields; the message adds words on WARN (8) and ERROR (9 or 10)
# Part F
find src -name '*.cs' | xargs wc -l # F1
echo a b c | xargs -n 1 # F2
find src -name '*.cs' | xargs -I{} echo file:{} # F3
touch 'my file.txt'
find . -name 'my*' | xargs ls # F4: fails, "my" and "file.txt" are two arguments
find . -name 'my*' -print0 | xargs -0 ls -l # F4: NUL separated, safe
rm 'my file.txt'
find src -name '*.cs' -exec wc -l {} + # F5: the same without a pipe. Prefer xargs when the
# input is not from find, or for -P parallel runs.
# Part G
grep ERROR app.log | cut -d' ' -f7- | sort | uniq -c | sort -rn | head -10 # G1: 4 messages, 16 to 20 each
cut -c12-16 app.log | sort | uniq -c | sort -rn | head -3 # G2: 18 at 10:58 and at 10:20, 16 at 10:09
sed -E 's#/(items|orders|users)/[0-9]+#/\1/ID#' app.log |
awk '{p=$4; ms=$6; sub(/ms/,"",ms); s[p]+=ms; n[p]++}
END {for (p in s) printf "%.0f %s\n", s[p]/n[p], p}' | sort -rn | head -3 # G3
awk '{n[$5]++} END {for (s in n) print s, n[s]}' app.log | sort # G4: 200 458, 404 69, 500 73
awk '{t++} $2=="ERROR" {e++} END {printf "%.1f%%\n", 100*e/t}' app.log # G5: 12.2%
sort -k6,6 -nr app.log | head -5 | cut -d' ' -f1,2,4,6 # G6: -k6,6 sorts on the duration field only
grep ERROR app.log | cut -c12-16 | sort | uniq -c | sort -rn | head -3 # G7
awk '{t++; if ($2=="ERROR") e++; if ($2=="WARN") w++; ms=$6+0; if (ms>max) max=ms}
END {print "total", t, "errors", e, "warnings", w, "slowest", max "ms"}' app.log # G8
# Part H
diff <(cut -d, -f1 people.csv | tail -n +2 | sort) <(sort notes.txt) # H1: diff needs two files, a pipe gives it one stream
wc -l <(grep ERROR app.log) # H2: prints "73 /dev/fd/63": the substitution is a file name
comm -12 <(grep -o '/api/[a-z]*' app.log | sort -u) <(printf '/api/items\n/api/zzz\n' | sort) # H3: /api/items
n=0; grep ERROR app.log | while read -r l; do n=$((n+1)); done; echo "pipe: $n" # H4: 0, wrong
n=0; while read -r l; do n=$((n+1)); done < <(grep ERROR app.log); echo "procsub: $n" # H5: 73
# H4/H5: each side of a pipe runs in a subshell, so the loop's n is lost when the pipe ends.
# With < <(...) the loop runs in your shell and keeps n.
paste -d' ' <(cut -d' ' -f2 app.log | head -3) <(cut -d' ' -f6 app.log | head -3) # H6
Clean up when you are finished:
cd ~ && rm -rf ~/tmp/pipes-lab