sort – Sorts all lines in a text file

The sort command is a Linux command that is used to sort all the lines in a text file. It can sort a file in ascending or descending order, based on the content of each line. The sort command is commonly used in shell scripts and in the command line to sort data in a file.

Overview

The sort command can be used in the following format:

sort [options] [file]

Where options are the various options available for the command, and file is the name of the file that needs to be sorted. If no file is specified, the command will read input from the standard input.

Examples

  1. To sort the contents of a file in ascending order:
sort file.txt
  1. To sort the contents of a file in descending order:
sort -r file.txt
  1. To sort the contents of a file and save the output to a new file:
sort file.txt > sorted_file.txt
  1. To sort the contents of a file and remove duplicate lines:
sort -u file.txt

Options

The following table lists the available options for the sort command:

Option Description
-r Sorts the file in reverse order (descending).
-n Sorts the file numerically.
-u Removes duplicate lines from the file.
-o Writes the sorted output to a new file.
-t Specifies a custom delimiter to use when sorting.

Troubleshooting tips

  • If the sort command is not working as expected, make sure that the file being sorted is a text file and not a binary file.
  • If the output of the sort command is not what you expected, check the file for any formatting issues, such as extra spaces or tabs.

Notes

  • The sort command can be used in combination with other commands, such as grep and sed, to perform more complex operations on files.
  • By default, the sort command sorts files in ascending order based on the ASCII value of each line.