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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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

Parameters explanation:

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

View the full sort manual here

Leave a Comment