In
this article, I will share my understanding of sort command with some examples.
One important point to notice is that the file contents must be on separate
line. If file contains only single line then we are not able to observe the
effect of sort command. Before jumping directly to examples, here are some of
its variations
To
sort file contents : sort filename.txt
To
sort according to column contents : sort
–k (column number) filename
To
sort in reverse order :
sort –r filename
To remove duplicates while
sorting : sort –u filename
- Sorting numeric contents
Suppose
file contains only numeric data then file contents are sorted in ascending
order of integer values as shown below.
$
cat file
015
004
016
009
003
018
002
020
$
sort file
002
003
004
009
016
018
020
- Sorting alphabetic contents
Suppose
file contains only alphabetic data then file contents are sorted alphabetically
as shown below.
$
cat file
Ashish
Gaigole
Siyaram
Vishwakarma
Deepak
Jaiswal
Dashrath
Sharma
$
sort file
Ashish
Gaigole
Dashrath
Sharma
Deepak
Jaiswal
Siyaram
Vishwakarma
- Sorting alpha-numeric contents
In
case file has both numeric and alphabetic data then first all numeric data is
sorted in ascending order followed by alphabetic data.
$ cat file
Ashish
Gaigole
Siyaram
Vishwakarma
Deepak
Jaiswal
Dashrath
Sharma
015
016
004
009
$
sort file
004
009
015
016
Ashish
Gaigole
Dashrath
Sharma
Deepak
Jaiswal
Siyaram
Vishwakarma
- Sorting file contents according to particular column values
$
cat file
Ashish
Gaigole 016 F-42
Siyaram
Vishwakarma 015 F-43
Deepak
Jaiswal 009 F-44
Dashrath
Sharma 004 F-41
$
sort –k 3 file : file is sorted according to third column in
file.
Dashrath
Sharma 004 F-44
Deepak
Jaiswal 009 F-41
Siyaram
Vishwakarma 015 F-43
Ashish
Gaigole 016 F-42
$
sort –k 4 file
: file is sorted according to fourth
column in file.
Deepak
Jaiswal 009 F-41
Ashish
Gaigole 016 F-42
Siyaram
Vishwakarma 015 F-43
Dashrath Sharma 004 F-44