Sorting Your Output

Problem

You would like output in a sorted order, but you don’t want to write (yet again) a custom sort function for your program or shell script. Hasn’t this been done already?

Solution

Use the sort utility. You can sort one or more files by putting the file names on the command line:

$ sort file1.txt file2.txt myotherfile.xyz

With no filenames on the command, sort will read from standard input so you can pipe the output from a previous command into sort:

$somecommands | sort

Discussion

It can be handy to have your output in sorted order, and handier still not to have to add sorting code to every program you write. The shell’s piping allows you to hook up sort to any program’s standard output.

There a few options to sort, but two of the three most worth remembering are:

$ sort -r

to reverse the order of the sort (where, to borrow a phrase, the last shall be first and the first, last); and

$ sort -f

to “fold” lower- and uppercase characters together; i.e., to ignore the case differences. This can be done either with the -f option or with a GNU long-format option:

$ sort --ignore-case

We decided to keep you in suspense, so see the next recipe, Sorting Numbers, for the third coolest sort option.

See Also

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.