0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use Sort Command in Linux: Syntax and Examples

Use the sort command in Linux to arrange lines of text alphabetically or numerically. The basic syntax is sort [options] filename, which outputs sorted lines to the terminal or a file.
📐

Syntax

The basic syntax of the sort command is:

  • sort [options] [file]

Here, file is the name of the text file to sort. If no file is given, sort reads from standard input.

Common options include:

  • -r: reverse the sort order
  • -n: sort numerically
  • -k: sort by a specific column
  • -o: write output to a file
bash
sort [options] [file]
💻

Example

This example sorts a file named names.txt alphabetically and outputs the result:

bash
cat > names.txt <<EOF
Charlie
Alice
Bob
EOF

sort names.txt
Output
Alice Bob Charlie
⚠️

Common Pitfalls

One common mistake is forgetting that sort outputs to the terminal by default and does not change the original file. Use -o filename to save sorted output back to a file.

Another pitfall is sorting numbers as text, which leads to incorrect order. Use -n to sort numerically.

bash
echo -e "10\n2\n1" > numbers.txt
sort numbers.txt
sort -n numbers.txt
Output
10 1 2 1 2 10
📊

Quick Reference

OptionDescription
-rSort in reverse order
-nSort numerically
-kSort by specific column (e.g., -k2)
-oWrite output to a file
-uOutput only unique lines

Key Takeaways

Use sort filename to sort lines alphabetically by default.
Add -n to sort numbers correctly instead of as text.
Use -r to reverse the sort order.
Use -o outputfile to save sorted results to a file.
Remember sort outputs to terminal unless redirected.