Shell “ls -l” sort by list column

It’s common to list the files on directory, but it usefull to list them order sometimes. One way to do that is to simply add the | sort -k instruction. The value of k is the column who will be ordered.

[cce_bash]
15:42 $ ls -lh
total 712
drwxr-xr-x 2 walter staff 68B Jan 19 15:39 dir1
drwxr-xr-x 2 walter staff 68B Jan 19 15:39 dir2
drwxr-xr-x 2 walter staff 68B Jan 19 15:39 dir3
-rw-r–r– 1 walter staff 1.6K Jan 19 15:40 file1.txt
-rw-r–r– 1 walter staff 68K Jan 19 15:40 file2.txt
-rw-r–r– 1 walter staff 139K Jan 19 15:41 file3.txt
-rw-r–r– 1 walter staff 70K Jan 19 15:41 file4.txt
-rw-r–r– 1 walter staff 71K Jan 19 15:42 file5.txt

15:42 $ ls -lh | sort -k5
total 712
drwxr-xr-x 2 walter staff 68B Jan 19 15:39 dir1
drwxr-xr-x 2 walter staff 68B Jan 19 15:39 dir2
drwxr-xr-x 2 walter staff 68B Jan 19 15:39 dir3
-rw-r–r– 1 walter staff 68K Jan 19 15:40 file2.txt
-rw-r–r– 1 walter staff 70K Jan 19 15:41 file4.txt
-rw-r–r– 1 walter staff 71K Jan 19 15:42 file5.txt
-rw-r–r– 1 walter staff 1.6K Jan 19 15:40 file1.txt
-rw-r–r– 1 walter staff 139K Jan 19 15:41 file3.txt

15:43 $ ls -lh | sort -k5n
total 712
-rw-r–r– 1 walter staff 1.6K Jan 19 15:40 file1.txt
-rw-r–r– 1 walter staff 68K Jan 19 15:40 file2.txt
drwxr-xr-x 2 walter staff 68B Jan 19 15:39 dir1
drwxr-xr-x 2 walter staff 68B Jan 19 15:39 dir2
drwxr-xr-x 2 walter staff 68B Jan 19 15:39 dir3
-rw-r–r– 1 walter staff 70K Jan 19 15:41 file4.txt
-rw-r–r– 1 walter staff 71K Jan 19 15:42 file5.txt
-rw-r–r– 1 walter staff 139K Jan 19 15:41 file3.txt
[/cce_bash]

Parameters explanation:

[cc]
-k, –key=POS1[,POS2]
start a key at POS1, end it at POS2 (origin 1)
-n, –numeric-sort
compare according to string numerical value
[/cc]

View the full sort manual here

Leave a Reply