How to Sort File Output in Linux

When working in the Linux terminal, you will frequently generate long lists of data. Whether you are viewing a directory containing hundreds of files, analyzing a server log, or reviewing a raw text file of customer names, reading unstructured, randomized data is inefficient. The sort command acts as a powerful filter, instantly reorganizing raw text into an alphabetical or numerical list, making it exponentially easier for a human or another script to process.

The Default Behavior of ‘sort’

The sort command operates on a simple principle: it reads a file line by line, looks at the very first character of each line, and arranges them in standard dictionary order (A to Z). It is important to note that sort does not permanently alter the original file; it merely prints the reorganized output to your screen.

Step-by-Step: Basic Alphabetical Sorting

Imagine you have a file named employees.txt containing a list of first names entered in random order.

  1. Open your terminal.
  2. Type the command:
    sort employees.txt
  3. Press Enter.

The terminal will instantly print the list of names, perfectly organized from A to Z. If you want to reverse the order (Z to A), you introduce the -r (Reverse) flag:

  1. Type: sort -r employees.txt
  2. Press Enter.

The Problem with Numbers

Sorting alphabetically is straightforward, but sorting numbers often causes confusion. If you have a file named scores.txt containing the numbers 2, 10, and 20, standard sort will arrange them like this: 10, 2, 20. Why? Because it sorts like a dictionary. It looks at the first character. “1” comes before “2”, so 10 is placed before 2.

To force the command to evaluate the entire number mathematically, you must use the -n (Numeric) flag.

  1. Type: sort -n scores.txt
  2. Press Enter.

The output will now correctly display: 2, 10, 20.

Piping Output to Sort

The true power of sort is unlocked when you combine it with other commands using a “pipe” (|). A pipe takes the output of one command and feeds it directly into the next.

For example, if you want to see all the files in a directory sorted by their size, you can use the ls -l command (which lists files) and pipe it into sort.

  • Type: ls -l | sort -nk 5

This command lists the files (ls -l), pipes the output to sort, tells it to sort numerically (-n), and crucially, tells it to look specifically at column 5 (-k 5), which is where the file sizes are located in the ls output. By mastering pipes and flags, sort becomes an indispensable data analysis tool.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.