Shell Toolkit (Cheatsheet)

Context: FIT1043_MOC, FIT2014_MOC Β· navigate β†’ inspect β†’ search/count β†’ sort β†’ cut columns β†’ pipe β†’ compress β†’ awk β†’ sed/tr/regex β†’ hand off Β· depth in Unix Shell (Bash); text-transform detail in Text Processing with sed and tr Β· FIT2014 = Lab 0 tooling 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.

πŸ“‚ Navigate & files

ToolMicro-syntaxJob / gotcha
cdcd dir Β· cd .. (up) Β· cd (home)change directory
lsls Β· ls -l (long) Β· ls -a (hidden)list directory
pwdpwdprint working directory
cp / mvcp src dst Β· mv src dstcopy / move-rename
mkdir / rmmkdir d · rm f · rm -r dmake dir / remove (⚠ no undo)

πŸ‘€ 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 output of one into the next
redirect… > out.txt (overwrite) Β· … >> out.txt (append)⚠ > replaces the file
wildcard *book*.txtmatch any characters
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

🀝 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 Cygwinprovides a Unix shell on Windows
macOS (Big Sur+)chsh -s /bin/bashdefault is now zsh; switch to bash

πŸ”€ 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.)

✍️ 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).