C.W.K.
Stream
Lesson 09 of 10 · published

cut and tr

~10 min · cut, tr, fields

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

cut — slice columns

cut picks fields out of structured input. Three modes:

  • cut -f 2 — second tab-separated field.
  • cut -d ',' -f 1,3 — first and third comma-separated.
  • cut -c 1-10 — first 10 characters of each line.
  • cut -d ' ' -f 2- — from field 2 to end.

Useful on CSV, TSV, and any line-oriented log with a fixed delimiter. For complex parsing prefer awk (next track).

tr — translate or delete characters

tr reads stdin character by character and translates. Two main forms:

  • tr 'a-z' 'A-Z' — uppercase.
  • tr -d ' ' — delete spaces.
  • tr -s ' ' — squeeze runs of spaces into one.
  • tr -c 'a-zA-Z0-9' '_' — replace anything not alphanumeric with _ (complement).

Real-world combos

  • Get unique IPs from a log: cut -d ' ' -f 1 access.log | sort -u
  • Lowercase a file: tr 'A-Z' 'a-z' < INPUT > output
  • Strip Windows line endings: tr -d '\r' < in.txt > out.txt
  • Replace tabs with spaces: tr '\t' ' '

Limits of cut

cut can't handle quoted CSV (commas inside quotes). For real CSV use csvkit, miller, or Python's csv module. cut is fine for simple delimited logs.

Code

Pull users from /etc/passwd·bash
cut -d ':' -f 1 /etc/passwd | head
# With shell
cut -d ':' -f 1,7 /etc/passwd | head
Normalize a name field·bash
echo '  John   Doe' \
  | tr -s ' '            \  # collapse whitespace
  | tr 'A-Z' 'a-z'       \  # lowercase
  | sed 's/^ //'         \  # leading space
  | tr ' ' '-'              # space -> dash

External links

Exercise

Run cut -d ':' -f 1 /etc/passwd | sort to list every user account. Then echo 'Hello World' | tr 'a-z' 'A-Z'. Finally try cat ~/.zshrc | tr -s ' ' | head to see how squeeze works on real text.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.