sort command in UNIX

post hero image

sort [OPTION]... [FILE]...
sort [OPTION]... --files0-from=F

Introduction

Write sorted concatenation of all FILE(s) to standard output. With no FILE (or when FILE is -), read standard input, just like nano does.

Options

The most useful options are:

  • -f, --ignore-case: fold lower case to upper case characters
  • -i, --ignore-nonprinting: consider only printable characters
  • -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)
  • --files0-from=F: read input from the files specified by NUL-terminated names in file F; If F is - then read names from standard input
  • -o, --output=FILE: write result to FILE instead of standard output
  • --parallel=N: change the number of sorts run concurrently to N

Examples

Given to-sort.txt file:

20MB
500kB
1TB
890 bits

Let’s try some sort options:

sort to-sort.txt
1TB
20MB
500kB
890 bits

# compare human readable numbers (e.g., 2K 1G)
# sort -h to-sort.txt
sort --sort=human-numeric to-sort.txt
890 bits
500kB
20MB
1TB

Given to-sort.txt file:

22 cats
5 clocks
10 dogs
80 cars

Let’s sort it:

sort to-sort.txt
10 dogs
22 cats
5 clocks
80 cars

# compare according to string numerical value
# sort --sort=numeric to-sort.txt
sort -n to-sort.txt
5 clocks
10 dogs
22 cats
80 cars

sort -n to-sort.txt --debug
sort: using ‘en_US.UTF-8’ sorting rules
5 clocks
_
________
10 dogs
__
_______
22 cats
__
_______
80 cars
__
_______

sort -n --output=sorted-file.txt to-sort.txt
cat sorted-file.txt
# ...

Quotes

Manual reference: