Linux Tips and Tricks

Linux Tips and Tricks

Sort command and its usage

September14

we have a file called alpha.txt and it contains the below characters.

1
2
3
4
5
6
7
8
9
10
$ cat alpha.txt 
A
Z
c
N
K
O
c
p
l

Sort the data alphabetically.
Note : data’s are sorted in ASCII values. ( A-65, p-112 )

1
2
3
4
5
6
7
8
9
10
$ sort alpha.txt 
A
K
N
O
Z
c
c
l
p

Now, we are using -f to ignore the case.

1
2
3
4
5
6
7
8
9
10
$ sort -f alpha.txt 
A
c
c
K
l
N
O
p
Z

-r is used to reverse the output.

1
2
3
4
5
6
7
8
9
10
$ sort -r -f alpha.txt 
Z
p
O
N
l
K
c
c
A

when we sort the numerical values, we need to -n option.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ cat num.txt 
33
21
35
18
9
0
24
12
 
$ sort -n num.txt 
0
9
12
18
21
24
33
35

Store the output in a new file. ( use -o option )

1
2
3
4
5
6
7
8
9
10
11
$ sort -o mynumoutput.txt -n num.txt 
 
$ cat mynumoutput.txt 
0
9
12
18
21
24
33
35

Sort unique data ( Omit the duplicate values )

1
2
3
4
5
6
7
8
9
10
11
12
$ cat duplicate.txt 
A
A
B
C
B
C
 
$ sort -u duplicate.txt 
A
B
C

Lets see how to sort the data by nth column

1
2
3
4
5
6
$ cat numeric.txt 
9723	10741	8605	30693
497	4017	21864	10039
9110	20910	626	3916
18359	22324	16905	7394
15708	3364	18818	31782

sort by 2rd column ( use -k2, -n for numeric )

1
2
3
4
5
6
$ sort -n -k2 numeric.txt 
15708	3364	18818	31782
497	4017	21864	10039
9723	10741	8605	30693
9110	20910	626	3916
18359	22324	16905	7394

sort by 3rd column ( use -k3, -n for numeric )

1
2
3
4
5
6
$ sort -n -k3 numeric.txt 
9110	20910	626	3916
9723	10741	8605	30693
18359	22324	16905	7394
15708	3364	18818	31782
497	4017	21864	10039

Now, we will see how to sort the data which is delimted by : (colon)

I simply, use the same numeric.txt file and i replaced all the \t (tab seperated) to : (colon)

1
2
3
4
5
6
7
8
$ sed -i 's/\t/:/g' numeric.txt 
 
$ cat numeric.txt 
9723:10741:8605:30693
497:4017:21864:10039
9110:20910:626:3916
18359:22324:16905:7394
15708:3364:18818:31782

Now sort by the 4th column. (use -k4 and -n for sort and -t for delimeter )

1
2
3
4
5
6
$ sort -t: -n -k4 numeric.txt 
9110:20910:626:3916
18359:22324:16905:7394
497:4017:21864:10039
9723:10741:8605:30693
15708:3364:18818:31782
posted under Uncategorized

Email will not be published

Website example

Your Comment:


Recent Comments

    Categories