Source From HereQuestionI want to sort a tab limited file in descending order according to the 5th field of the records.
How-ToWe can leverage command
sort. For example:
// Default is sort by file name in asc order
# ls -hl
total 12K
-rw-r--r--. 1 root root 4 Mar 27 22:19 test01
-rw-r--r--. 1 root root 10 Mar 27 22:19 test02
-rw-r--r--. 1 root root 2 Mar 27 22:19 test03
// Let's reverse it to descending order
// -r, --reverse: reverse order while sorting
# ls -hlr
total 12K
-rw-r--r--. 1 root root 2 Mar 27 22:19 test03
-rw-r--r--. 1 root root 10 Mar 27 22:19 test02
-rw-r--r--. 1 root root 4 Mar 27 22:19 test01
// How about sorting in field 5 which is the size of file
// -n, --numeric-sort: compare according to string numerical value
// -k, --key=KEYDEF: sort via a key; KEYDEF gives location and type
# ls -hl | sort -n -k5
total 12K
-rw-r--r--. 1 root root 2 Mar 27 22:19 test03
-rw-r--r--. 1 root root 4 Mar 27 22:19 test01
-rw-r--r--. 1 root root 10 Mar 27 22:19 test02
// Let's revert it in descending order
// -r, --reverse: reverse the result of comparisons
# ls -hl | sort -nr -k5
-rw-r--r--. 1 root root 10 Mar 27 22:19 test02
-rw-r--r--. 1 root root 4 Mar 27 22:19 test01
-rw-r--r--. 1 root root 2 Mar 27 22:19 test03