Site icon LinuxCommands.site

sort command tutorial in linux/unix with examples and use cases

linux sort command – sort lines of text files.

As the name implies, the linux sort command is used to sort files. It supports sorting of numbers, letters, specific columns, etc.

syntax

sort [OPTION]... [FILE]...

options

examples

1.sorted file

➜ cat test.log
hello:21
var:98
mear:29
awk:80
follow:10
➜ sort test.log
awk:80
follow:10
hello:21
mear:29
var:98

2. sort files in reverse order

➜ cat test.log
hello:21
var:98
mear:29
awk:80
follow:10
➜ sort -r test.log
var:98
mear:29
hello:21
follow:10
awk:80

3. separate fields and sort by key

Separated by “:” and sorted by the second column

➜ cat test.log
hello:21
var:98
mear:29
awk:80
follow:10
➜ sort -t ":" -k 2 test.log
follow:10
hello:21
mear:29
awk:80
var:98

You can also use the linux awk command to separate and then use the Linux sort command to sort.

➜ cat test.log
hello:21
var:98
mear:29
awk:80
follow:10
➜ awk -F':' '{print $1 " " $2}' test.log | sort -k 2
follow 10
hello 21
mear 29
awk 80
var 98

4. sort file/directory sizes in human readable format

➜ du -sh * | sort -h

5. sort randomly and write to new file

➜ sort -R test.log -o test-2.log

6. sort multi column sort

The third column is sorted in ascending order, if the third column is the same, the second column is sorted in descending order.

➜  sort -t : -k3 -k2rn test-1.log

Exit mobile version