Linux sort command

The sort command in Linux and Unix-like operating systems is used to sort lines of text in a file or from standard input. It arranges the lines in either ascending or descending order based on specified criteria, such as alphabetically, numerically, or based on specific fields within each line.

The basic syntax of the sort command is as follows:

sort [options] [file(s)]

Here, [options] represents the various flags and parameters you can use with the command, and [file(s)] refers to the file or files you want to sort. If no file is specified, sort reads input from standard input.

Some commonly used options with sort include:

  • -r: Sorts in reverse order (descending).
  • -n: Sorts numerically.
  • -f: Performs a case-insensitive sort.
  • -k: Specifies a specific field to sort on (e.g., -k 2 for the second field).
  • -t: Specifies a custom field separator (default is whitespace).
  • -u: Removes duplicate lines.
  • -o: Specifies an output file.

To use the sort command, open a terminal and enter the command followed by the desired options and the file(s) you want to sort. Here are a few examples:

  1. Sort lines in a file alphabetically:
sort filename
  1. Sort lines in reverse order numerically:
sort -r -n filename
  1. Sort lines based on the second field, numerically:
sort -k 2 -n filename
  1. Sort lines ignoring case and remove duplicates:
sort -f -u filename
  1. Sort lines from standard input:
command | sort

These are just a few examples, and there are many more options and variations you can use with the sort command. To explore additional options and information, you can refer to the sort command’s manual page by typing man sort in the terminal.