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

  • -b, –ignore-leading-blanks
    ignore leading blanks
  • -d, –dictionary-order
    consider only blanks and alphanumeric characters
  • -f, –ignore-case
    fold lower case to upper case characters
  • -g, –general-numeric-sort
    compare according to general numerical value
  • -i, –ignore-nonprinting
    consider only printable characters
  • -M, –month-sort
    compare (unknown) < ‘JAN’ < … < ‘DEC’
  • -h, –human-numeric-sort
    compare human readable numbers (e.g., 2K 1G)
  • -n, –numeric-sort
    compare according to string numerical value
  • -R, –random-sort
    shuffle, but group identical keys. See shuf(1)
  • –random-source=FILE
    get random bytes from FILE
  • -r, –reverse
    reverse the result of comparisons
  • –sort=WORD
    sort according to WORD: general-numeric -g, human-numeric -h, month -M, numeric -n, random -R, version -V
  • -t, –field-separator=SEP
    use SEP instead of non-blank to blank transition
  • -k, –key=KEYDEF
    sort via a key; KEYDEF gives location and type
  • -m, –merge
    merge already sorted files; do not sort
  • -u, –unique
    with -c, check for strict ordering; without -c, output only the first of an equal run

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

Add a Comment

Your email address will not be published.