← back to latest

Sort a CSV by any column without opening a spreadsheet

sort -t, -k3 -nr sales.csv | head -20

anatomy

sort
Sort lines of text. Reads from a file or stdin and writes sorted output to stdout.
-t,
Use comma as the field delimiter instead of whitespace.
-k3
Sort by the third field. Change the number to target a different column.
-n
Numeric sort, so 10 comes after 9 rather than after 1.
-r
Reverse the order, putting the largest values first.
head -20
Keep only the top 20 rows.

Sample output

East,Widgets,94200,Q3
West,Widgets,87500,Q2
East,Gadgets,76300,Q1

The third column is revenue, and the output is sorted from highest to lowest.

When you would reach for it

A quick look at a CSV export before deciding whether it is worth importing into a database or opening in a spreadsheet. Also useful in pipelines that feed into other commands.

Gotchas

  • If any field contains a comma inside quotes, sort -t, will split on the wrong boundary. For serious CSV parsing, use csvtool or mlr (Miller).
  • Headers will sort into the output. Pipe through tail -n +2 first to skip the header, or use head -1 file; tail -n +2 file | sort ... to preserve it.

Variants

$ sort -t$'\t' -k3 -nr data.tsv | head -20

Tab-separated files. Use $'\t' as the delimiter

$ mlr --csv sort-by -nr revenue sales.csv | head -20

Miller. Handles quoted fields and headers correctly

lineage

sort appeared in Version 1 Unix in 1971, written by Ken Thompson. It was one of the first tools designed around the Unix philosophy of reading from stdin and writing to stdout, making it composable with pipes before pipes were even formalized. The original implementation sorted entire lines alphabetically. Field-based sorting with -t and -k came later, evolving through Version 7 Unix and into POSIX. The modern -k syntax (replacing the older +pos -pos notation) was standardized in POSIX.2 in 1992, though both forms coexisted for years. GNU coreutils added -h for human-readable numeric sort in 2009, and --parallel for multi-threaded sorting of large files. Despite fifty years of alternatives, sort remains the default answer to ordering text on the command line, largely because it requires no configuration and handles the common case in a single flag.