Category Archives: commands

Linux : sort command

I have a file called test.txt
File content ->

1 2 3
3 2 1
2 3 1
2 1 3

If we want to sort it on the first column/field

$ sort +0 -1 test.txt
1 2 3
2 1 3
2 3 1
3 2 1

Sort on the second field/column

$ sort +1 -2 test.txt
2 1 3
1 2 3
3 2 1
2 3 1

On third column

$ sort +2 -3 test.txt
2 3 1
3 2 1
2 1 3
1 2 3

Sort on the first and the second column
2 3 1
3 2 1
2 1 3
1 2 3
We should get the 1 2 3 as the first row, because 1 2 is the lowest

$ sort +0 -2 test.txt
1 2 3
2 1 3
2 3 1
3 2 1

Sort it on second and third columns

$ sort +1 -3 test.txt
2 1 3
3 2 1
1 2 3
2 3 1

If we want to specify a separator (default space)

sort -t <separator> <file>
Tagged