sort Command in Linux

Topics Covered

Overview

The sort command in Linux is a versatile utility that sorts lines of text from standard input or a file. It is useful for organizing, analyzing, and filtering data in files. The command offers various options to customize the sorting process, such as sorting by numerical values, month names, or case-insensitive.

Linux sort Command Syntax

The syntax for the sort command is as follows:

Where:

  • OPTION: Flags that modify the sorting behavior of the command. Multiple options can be combined.
  • FILE: The input file(s) to be sorted. If no file is provided, the command reads from standard input.

sort Command Options:

  • -b: Ignore leading blanks (spaces and tabs) when determining sort keys.
  • -c: Check if the input is already sorted and output any unsorted lines.
  • -f: Perform case-insensitive sorting.
  • -n: Sort numerically.

Example Usages

  • Sort a file alphabetically:

    Output:

    Explanation: This command sorts the lines in file.txt alphabetically and displays the output.

  • Sort a file numerically:

    Output:

    Explanation: This command sorts the lines in numbers.txt numerically and displays the output.

Tips

  • To sort in reverse order, use the -r option.

  • To sort by a specific column, use the -k option.

Advanced Use Cases of sort Command in Linux

  • Sort by the second column numerically:

    Output:

    Explanation: This command sorts the lines in file.txt based on the second column's numeric values and displays the output.

  • Sort by month name:

    Output:

    Explanation: This command sorts the lines in months.txt based on the month names and displays the output.

  • Sort and remove duplicates:

    Output:

    Explanation: This command sorts the lines in file.txt, removes duplicate lines, and displays the unique sorted output.

Conclusion

  • The sort command is a versatile tool for sorting lines of text in files or standard input.

  • Various options can be combined to customize the sorting process.

  • It can handle numerical, alphabetical, and month-based sorting.