bash sort - ghdrako/doc_snipets GitHub Wiki

Sort by Number

$ sort -n cities2.txt
1.38 Amsterdam
1.82 Hamburg
2.15 Paris
3.90 Los Angeles
8.18 New York City
21.45 Beijing

sort -n can help us to sort lines by decimal numbers. However, it cannot sort signed binary or hexadecimal numbers correctly.

Sort in Reverse Order

$ sort -nr cities2.txt 
21.45 Beijing
8.18 New York City
3.90 Los Angeles
2.15 Paris
1.82 Hamburg
1.38 Amsterdam

Sort by Month

$ sort -M months.txt
January
August
October
November
December

Sort by ASCII Character Code

$ sort ascii.txt
a
A
b
B
c
C

instead sort lines by ASCII code, we must set the environment variable LC_ALL=C, so that we force sorting to be byte-wise.

$ LC_ALL=C sort ascii.txt
A
B
C
a
b
c

LC_ALL=C temporarily only for the sort command execution. It won’t change the LC_ALL value in the current shell.

Write the Sorted Output to a File

$ sort -o ascii_result.txt ascii.txt
$ sort ascii.txt > ascii_result.txt
$ echo "$(sort cities.txt)" > cities.txt

Sort and Remove Duplicates

$ sort -u dup.txt 

Sort by Keys

Version sort

-V, --version-sort natural sort of (version) numbers within text

last_version==$(echo -e "$versions" | grep -v "p" |sort -V | tail -n1)