2016年3月27日 星期日

[Linux 常見問題] unix sort descending order

Source From Here
Question
I want to sort a tab limited file in descending order according to the 5th field of the records.

How-To
We 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


沒有留言:

張貼留言

[ Python 常見問題 ] python generator “send” function purpose?

Source From  Here   Question   Can someone give me an example of why the "send" function associated with Python generator function...