🎓 A1Learner
🔍
0 of 50 lessons completed

Shell Sorting and Counting

sort orders the lines of a file. Lines come back in alphabetical order by default.

Sort lines

sort orders the shopping lines from a to z.

sort shopping.txt

Sort numbers

sort -n orders 2 before 10, by value.

echo 10 > numbers.txt
echo 2 >> numbers.txt
echo 30 >> numbers.txt
sort -n numbers.txt

Drop repeats

sort puts the two apples lines together, and uniq keeps one of them.

sort shopping.txt | uniq

uniq needs sorted input

Without sort, the two apples lines sit apart, so uniq keeps both.

uniq shopping.txt

Count lines, words and bytes

wc prints the line count, the word count and the byte count.

wc notes.txt

Example

sort shopping.txt | uniq > unique.txt
cat unique.txt
wc -l unique.txt

Key points

  • Use sort file to order lines from a to z.
  • Use sort -n to order numbers by value, not by first digit.
  • Use uniq to drop lines that repeat the line before them.
  • uniq needs sorted input, because it only drops repeats that sit together.
  • Use wc to count lines, words and bytes in a file.

In this example, sort orders the shopping lines and uniq drops the repeat. The result goes into unique.txt. Then cat prints the four lines, and wc -l counts them.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does uniq need sorted input?