Shell Toolkit (Cheatsheet)

Context: FIT1043_MOC, FIT2014_MOC, FIT2109_MOC Β· locate β†’ navigate β†’ inspect β†’ search/count β†’ sort β†’ cut columns β†’ pipe β†’ compress β†’ awk β†’ sed/tr/regex β†’ permissions/streams/status β†’ hand off Β· depth in Unix Shell (Bash); text-transform detail in Text Processing with sed and tr; execution mechanics in Shell Execution Model (Permissions, Processes, Streams) Β· FIT2014 = Lab 0 tooling Β· FIT2109 = W1 systems angle Read protocol: scan tables β†’ attempt the practice blank β†’ follow the pattern-note link only where you failed.

Quick Revision

  • 🎯 Objective: explore/clean a huge text/CSV file from the command line without loading it into memory βž” chain small tools with pipes, then hand the reduced file to R/Python.
  • ⚑ Key Constraint: the pipe | is buffered + line-at-a-time β€” memory stays bounded so it scales past RAM; > overwrites a file, | feeds the next program β€” never confuse them.

🧩 Pipeline Anatomy (execution order)

cat big.csv.gz | gunzip | awk -F',' 'NR>1 {print $6,$14}' | sort -n | head
#   └─sourceβ”€β”€β”˜  β””decompβ”˜  └──select cols, skip headerβ”€β”€β”˜  β””numericβ”˜ β””peekβ”˜
# reads L→R; each stage streams rows to the next as needed (nothing fully in memory)
  • Order βž” source β†’ transform β†’ filter β†’ sort β†’ view/save; put cheap filters early (less data flows downstream).
  • Save instead of view βž” replace the final head/less with > out.txt to persist the result.
  • Only the LAST stage sets the exit status βž” a mid-pipeline failure is invisible; set -o pipefail in a script propagates it.

🧭 Location & pathnames

ToolMicro-syntaxJob / gotcha
pwdpwdprint working directory β€” first move when a command β€œmysteriously” fails
absolute path/Users/student/fit2109/week1starts at root / β†’ start-independent
relative pathdata/rawresolved from the cwd β†’ meaning changes with location
. / .. / ~cd .. Β· cd ../.. Β· cd ~current dir Β· parent Β· home
manman ls Β· ls --helplook up every option for a command
shortcutsTab Β· Ctrl-C Β· ↑complete name Β· kill running process (not copy) Β· recall last command
echo $SHELLecho "$SHELL"which interactive shell (Bash $ vs Zsh %); a #!/usr/bin/env bash script runs in Bash regardless

πŸ“‚ Navigate & files

ToolMicro-syntaxJob / gotcha
cdcd dir Β· cd .. (up) Β· cd (home)change directory
lsls Β· ls -l (long) Β· ls -a (hidden)list directory
cp / mvcp src dst Β· mv src dstcopy (original stays) / move-rename (old path disappears)
mkdir / rmmkdir d · rm f · rm -r dmake dir / remove (⚠ no undo)
touchtouch fcreate empty file, or update its timestamp

πŸ‘€ Inspect / read

ToolMicro-syntaxJob / gotcha
lessless file β€” space/↑↓ page, /kw search, shift+g end, q quitreads only the start β†’ instant on huge files
catcat filedump whole file (or concatenate)
head / tailhead -n 20 file Β· tail -n 20 filefirst / last N lines (default 10)
wcwc -l file (lines) Β· wc (lines/words/chars)⚠ must read the whole file β†’ slow on huge files

πŸ” Search & count

ToolMicro-syntaxJob / gotcha
grepgrep "elephant" fileprint lines containing the pattern
grep -cgrep -c "kw" filecount matching lines (= grep … | wc -l)
grep -i / -vgrep -i "kw" Β· grep -v "kw"case-insensitive Β· invert (non-matching)
count matchesgrep "kw" file | wc -l (pipe to count)classic filter-then-count

πŸ”’ Sort

ToolMicro-syntaxJob / gotcha
sortsort filealphabetical (default)
sort -nsort -n filenumeric (else 10 sorts before 2)
sort -rsort -r filereverse order
sort -ksort -k2,2 filesort by column 2
sort -tsort -t',' -k2,2nset delimiter , + numeric key
uniqsort file | uniq -ccount duplicates (⚠ needs sorted input)

βœ‚οΈ Columns

ToolMicro-syntaxJob / gotcha
cut -fcut -f 3 filecolumn 3 β€” assumes tab delimiter
cut -dcut -d',' -f 3 fileset delimiter to comma
awk colsawk -F',' '{print $6,$7,$14}'columns 6/7/14; -F',' = comma delimiter; $0 = whole line

🧠 awk power (one line at a time β†’ scales)

TaskMicro-syntaxNote
set delimiterawk -F',' '…'-F = field separator
row-range filterawk -F',' 'NR>1000 && NR<=1500 {print $6}'NR = current line number
skip headerawk -F',' 'NR>1 {print $6}'drop line 1
random sampleawk 'rand()<1/100 {print $0}'keep ~1% of rows
value filter (+header)awk -F',' '$22=="\"California\"" || NR==1 {print $6}'escape embedded quotes \"

πŸ”€ Pipes, redirect, wildcards, compression

ToolMicro-syntaxJob / gotcha
pipeprog1 | prog2stream stdout of one into stdin of the next β€” stderr does NOT travel down a pipe
redirect out… > out.txt (overwrite) Β· … >> out.txt (append)⚠ > replaces the file; retargets stdout only
redirect inprog < in.txtfeed a file to stdin
redirect err… 2> err.txt Β· … 2>/dev/nullcapture / discard stderr separately
both… > out.txt 2> err.txtsplit results from diagnostics
wildcard *book*.txt Β· ls *.shshell expands to filenames before the command runs
bracket rangebook[1-5].txtmatch a range (books 1–5 only)
gunzipgunzip file.gz (in place) Β· cat f.gz | gunzip | … (stream)decompress .gz
unzip -punzip -p file.zip | …stream a zip to a pipe β€” no huge temp file
backgroundmyprogram &run in background; scripts can be shell programs

πŸ” Permissions & execution (FIT2109 β€” details βž” Shell Execution Model (Permissions, Processes, Streams))

ItemMicro-syntaxJob / gotcha
read the string-rwxr-xr-x = type | owner | group | others- file, d directory; a - in a slot = permission absent
r w xread Β· write Β· executeon a directory, x means traverse (needed to cd in)
chmodchmod u+x fileadd execute for owner; changes metadata only, never file contents
ls -lls -l file⚠ run this before guessing why a script won’t run
$PATHecho $PATHcolon-separated dirs, scanned left to right; . is not on it
bare namerun.sha lookup request β†’ command not found if not on $PATH
explicit path./scripts/run.shcontains / β†’ skips lookup, used literally
builtin vs externalcd (builtin) vs ls (program on disk)cd must be builtin β€” it changes the shell’s own cwd
shebang#!/usr/bin/env bashscript runs in Bash whatever your interactive shell is
ps / $$ps Β· echo $$process status (pid, ppid, comm) Β· PID of the current shell
exit statusecho $?0 = success, nonzero = failure β€” independent of what was printed

Three signature errors = three stages βž” command not found (lookup) Β· permission denied (found, but no x) Β· no such file or directory (path resolves to nothing). The message is the diagnosis.

πŸ”€ Text transform β€” sed / tr / grep-regex (FIT2014 β€” details βž” Text Processing with sed and tr)

ToolMicro-syntaxJob / gotcha
sed substitutesed 's/pat/rep/' filefirst match per line; file unchanged (stdout)
sed globalsed 's/pat/rep/g' fileg = every match on the line
sed backrefsed 's/2\([0-9]*\)/3\1/'\(...\) captures, \1..\9 reuse in replacement
sed delete charssed 's/[^a-zA-Z]//g'replace-with-nothing = delete
char class[aeiou] Β· [a-z] Β· [^a-z]set Β· range (ASCII) Β· complement (^ first)
anchors^pat Β· pat$ Β· ^pat$starts / ends / whole line
tr maptr 'A-Z' 'a-z'per-character map (not words)
tr -d / -str -d 'aeiou' Β· tr -s ' 'delete listed Β· squeeze runs to one
grep regexgrep '[aeiou][aeiou]' f Β· grep '^a.*b$' fgrep patterns are regexes (Regular Expressions)

(⚠ POSIX BRE: grouping/repetition are escaped β€” \(...\), \{n\}; bare () {} are literal. Opposite of the theory notation.)

🀝 Hand-off & setup

TaskMicro-syntaxNote
shell β†’ Rawk … > out.txt then in R: df <- read.table('out.txt', header=TRUE)reduce first, analyse in R
Windows setupinstall Cygwin or WSLprovides a Unix shell on Windows
macOS (Big Sur+)chsh -s /bin/bashdefault is now zsh (% prompt); switch to bash

✍️ Integration Practice

⚠️ Common Mistakes

  • πŸ’‘ > overwrites, | chains βž” redirect replaces the target file; pipe feeds the next program.
  • πŸ’‘ Mind the delimiter βž” cut -f assumes tab; for CSV use awk -F',' or cut -d','. Check the real delimiter first (/<tab> search in less).
  • πŸ’‘ wc/sort/uniq read the whole file βž” slow + memory-heavy on huge files; less/head only read the start β†’ instant. Put cheap filters before them.
  • πŸ’‘ sort is alphabetical by default βž” add -n for numbers, and uniq only collapses adjacent duplicates (so sort | uniq).
  • πŸ’‘ > does not capture errors βž” it retargets stdout only; stderr still hits the screen and needs 2>.
  • πŸ’‘ Empty output β‰  success βž” check echo $?; and a pipeline’s status is only its last stage’s.
  • πŸ’‘ permission denied β‰  file missing βž” that is no such file or directory. Match the message to the stage before acting.