In Unix, how do I use the sort command?

The sort command sorts the contents of a file, in numeric or alphabetic order, and prints the results to standard output (usually the terminal screen). The original file is unaffected.

For example, if filename is a file containing a list of words, at the Unix prompt, you would enter:

  sort filename

This will print the list to the screen in alphabetical order (numbers first, then capital words, then lowercase words). To eliminate any duplicate entries in the list, use:

  sort -u filename

To sort case-insensitively, use:

  sort -f filename

To sort case-insensitively and in reverse order, use:

  sort -fr filename

As with many Unix commands, you can redirect the output to a new file:

  sort filename > newfilename

The output of the sort command will then be stored in a file named newfilename in the current directory.

You can also pipe the output of the sort command into other Unix commands, for example:

  sort filename | more

This sends the output through the more command for easy reading.

To print only the first word of each line, enter:

  sort filename | cut -f1 -d" " 

The cut command selects the field specified by the -f option and distinguishes fields by the delimiter character specified by the -d option, a space in this example.

To view the online manual for the sort command, at the Unix prompt, enter:

  man sort 

At Indiana University, for personal or departmental Linux or Unix systems support, see At IU, how do I get support for Linux or Unix?

This is document afjb in the Knowledge Base.
Last modified on 2018-10-10 18:26:50.

Contact us

For help or to comment, email the UITS Support Center.