Linux and Bash course menu
Linux Text Processing: sort, uniq, cut, tr and paste
Process text from the command line: sort lines, remove and count duplicates with uniq, extract columns with cut, translate characters with tr, and build a top 10 report.
These small tools turn the command line into a quick data tool. We use this file:
cat staff.csvname,city,department,salary
Asha,Hyderabad,Engineering,90000
Ravi,Pune,Sales,55000
Meena,Hyderabad,Engineering,105000
Karan,Chennai,Support,42000
Divya,Pune,Engineering,88000
Arjun,Hyderabad,Sales,61000sort#
sort orders lines alphabetically. -n sorts numbers, -r reverses, -t sets the separator, and -k chooses the column:
tail -n +2 staff.csv | sort -t, -k4 -nr | head -n 3Meena,Hyderabad,Engineering,105000
Asha,Hyderabad,Engineering,90000
Divya,Pune,Engineering,88000Without -n, 9 would sort after 10, because text is compared one character at a time.
cut#
cut extracts columns. -d is the separator and -f lists the fields:
cut -d, -f1,4 staff.csv | head -n 3name,salary
Asha,90000
Ravi,55000cut handles single-character separators only. For columns separated by runs of spaces, use awk.
uniq#
uniq removes adjacent duplicates, so always sort first. -c counts:
tail -n +2 staff.csv | cut -d, -f2 | sort | uniq
echo ---
tail -n +2 staff.csv | cut -d, -f2 | sort | uniq -cChennai
Hyderabad
Pune
---
1 Chennai
3 Hyderabad
2 Punesort -u is a shortcut for sort | uniq.
The top N pattern#
This pipeline answers "what are the most common values?". Learn it by heart:
tail -n +2 staff.csv | cut -d, -f3 | sort | uniq -c | sort -nr | head -n 2 3 Engineering
2 SalesYou will use it for top IP addresses, top error messages, and much more. The log report project relies on it.
tr#
tr translates or deletes characters:
echo "Laviyx Learn" | tr 'a-z' 'A-Z'
echo "a,b,c" | tr ',' '\n'
echo "Order 1042" | tr -s ' '
echo "Phone: 98-76-54" | tr -d '-'LAVIYX LEARN
a
b
c
Order 1042
Phone: 987654-s squeezes repeats, and -d deletes characters.
paste#
paste joins lines side by side:
printf 'a\nb\n' > left.txt
printf '1\n2\n' > right.txt
paste -d: left.txt right.txta:1
b:2Count things#
wc -l counts lines, so add it to the end of a pipe:
tail -n +2 staff.csv | grep -c Hyderabad
tail -n +2 staff.csv | cut -d, -f2 | sort -u | wc -l3
3Common mistakes#
Practice#
Practice exercise
Print the name of the highest-paid person in Pune.
Show solution
grep Pune staff.csv | sort -t, -k4 -nr | head -n 1 | cut -d, -f1DivyaKey takeaway#
Next: Editing Text with sed.
Finished this lesson?