How to sort lines of text files in Linux?

LinuxOperating SystemOpen Source

To sort lines of text files, we use the sort command in the Linux system.

The sort command is used to prints the lines of its input or concatenation of all files listed in its argument list in sorted order. The operation of sorting is done based on one or more sort keys extracted from each line of input. By default, the entire input is taken as the sort key.

Syntax

The general syntax of the sort command is as follows.

sort [OPTION]... [FILE]...
sort [OPTION]... --files0-from=F

Brief description of options available in the sort command.

Sr.No.Option & Description
1-b, --ignore-leading-blanks
Ignore leading blanks.
2-d, --dictionary-order
Consider only blanks and alphanumeric characters.
3-f, --ignore-case
Fold lower case to upper case characters.
4-g, --general-numeric-sort 
Compare according to general numerical value.
5-i, --ignore-nonprinting
Consider only printable characters.
6-M, --month-sort
Compare (unknown) <’JAN’ <...<’DEC’.
7-h, --human-numeric-sord
Compare human-readable numbers.
8-n, --numeric-sort
Compare according to string numerical value.
9--random-source=FILE
Get random bytes from the FILE.
10-r, --reverse
Reverse the result of comparisons.
11--sort=WORD
Sort according to the WORD.
12--help
Display this help and exit
13--version
Output version information and exit.

Here, we will create a file using the cat command and sort this file using the sort command in the Linux system.

$ cat >text.txt
Sid
Vikash
Gaurav
^C
$ sort text.txt
Gaurav
Sid
Vikash

Here, we will sort a file in the reverse order using the -r or --reverse option with the sort command in the Linux operating system.

$ cat >text.txt
Sid
Vikash
Gaurav
^C
$ sort text.txt
Vikash
Sid
Gaurav

In the above example, we already saw that how can we sort a file but output of the sort command on standard output. Here, we will save output into a new file in the file system.

$ sort text.txt > newtext.txt

After executing the above command, a new file will be created with the newtext.txt name.

To check more information and options with descriptions about the sort command, we use the --help option with the sort command as shown below.

$ sort --help

To check in which version the sort command is working, we use the --version option with the sort command in the Linux system as shown below.

$ sort --version
raja
Published on 01-Jul-2021 15:38:52
Advertisements