>_ IzzyLab

Hands-on task

This task is step 4 of the course “First steps with text”

Put things in order

easy~5 min

The /root/data directory has two lists:

  • users.txt — employee logins;
  • sizes.txt — file sizes in megabytes.
  1. Save the logins in alphabetical order (a to z) to /root/users_sorted.txt.
  2. Save the sizes from the largest to the smallest to /root/sizes_sorted.txt.

Don't change the original files.

What you'll practise:
  • sort
  • sort -n
  • sort -r
  • numbers vs text

Topic breakdown

sort reads lines and prints them in order. By default lines are compared as text — by the first character, then by the second if those are equal, and so on.

With numbers that goes wrong: as text, 100 is less than 25, because 1 comes before 2. Flags change the behavior:

  • -n — compare as numbers;
  • -r — reverse order (largest to smallest, z to a).
printf '25\n100\n3\n' | sort      # 100, 25, 3 — as text
printf '25\n100\n3\n' | sort -n   # 3, 25, 100 — as numbers

sort doesn't change the file itself — it only prints the sorted result.

What's checked

  1. users_sorted.txt holds all the logins in alphabetical order
  2. sizes_sorted.txt holds all the sizes from largest to smallest

What it looks like