Bash Tutorial · Pipes and Text Processing · Lesson 12 of 30
Bash sort, uniq, cut and tr
Sort lines, remove duplicates, extract columns and translate characters.
The toolbox
sortsorts lines:-nnumeric,-rreverse,-k2by the second field,-t,with a comma separator,-uunique.uniqremoves adjacent duplicates (sort first);uniq -ccounts them.cut -d, -f2extracts the second comma-separated field;cut -c1-5the first five characters.tr 'a-z' 'A-Z'translates characters;tr -d '\r'deletes them (handy for Windows line endings).
cat > visits.txt <<'EOF'
/home
/orders
/home
/cart
/home
/orders
EOF
sort visits.txt | uniq -c | sort -rn
echo ---
printf 'ana,DE,31\nben,US,25\nchen,DE,40\n' > people.csv
sort -t, -k3 -n people.csv | cut -d, -f1
echo "make me loud" | tr 'a-z' 'A-Z'
Output
3 /home
2 /orders
1 /cart
---
ben
ana
chen
MAKE ME LOUDRun this on your computer — see “Get Started” for setup.
Test yourself
Why do you usually run sort before uniq?
uniq can't read filesuniq only removes duplicates that are next to each othersort removes duplicates itselfIt's faster
Show answer
Answer: uniq only removes duplicates that are next to each other