Intro to sort
The sort command will sort the lines in a text file according to various criteria. The default sort order is ASCII character order, which has punctuation characters first, then numbers, then upper case letters, then lower case letters.
Example of an unsorted file:
$ cat file1 sarah . John 7 carol Claire eric 43 ,
Sorting the file:
$ sort file1 , . 43 7 Claire John carol eric sarah
Note that 43 comes before 7. This is because sort is not comparing them as numbers, but it is sorting them according to the ASCII character order. 4 comes before 7 in the ASCII character order, so any string starting with a 4 will come before any string starting with a 7.
To sort a file numerically, you would use the -n option.
File containing numbers:
$ cat num1 100 3 47658 23 8 2398
Default (ASCII order) sort:
$ sort num1 100 23 2398 3 47658 8
Numeric sort:
$ sort -n num1 3 8 23 100 2398 47658
Real Life Example
A common use of numeric sort is seeing what files or directories are using the most space.
Checking disk usage:
$ du -sk * 39232 bin 238 list.txt 92876 mail 1623 notes 864328 photos
Sorting disk usage:
$ du -sk * | sort -n 238 list.txt 1623 notes 39232 bin 92876 mail 864328 photos
Or you can use the -r flag in conjunction with the -n flag to sort in reverse numeric order:
$ du -sk * | sort -rn 864328 photos 92876 mail 39232 bin 1623 notes 238 list.txt
Summary
The sort command will sort a file according to ASCII character order by default. Use -n to sort by numeric value. Use -r to reverse the order of a sort.
Filed under: unix |
Tags: basic, command, sort, unix
Search
You are currently browsing the Miscinformation weblog archives.
No Responses to “Intro to sort”
Leave a Reply