How can I list (ls) the 5 last modified files in a directory? How can I list (ls) the 5 last modified files in a directory? linux linux

How can I list (ls) the 5 last modified files in a directory?


Try using head or tail. If you want the 5 most-recently modified files:

ls -1t | head -5

The -1 (that's a one) says one file per line and the head says take the first 5 entries.

If you want the last 5 try

ls -1t | tail -5


The accepted answer lists only the filenames, but to get the top 5 files one can also use:

ls -lht | head -6

where:

-l outputs in a list format

-h makes output human readable (i.e. file sizes appear in kb, mb, etc.)

-t sorts output by placing most recently modified file first

head -6 will show 5 files because ls prints the block size in the first line of output.

I think this is a slightly more elegant and possibly more useful approach.

Example output:

total 26960312-rw-r--r--@ 1 user staff 1.2K 11 Jan 11:22 phone2.7.py-rw-r--r--@ 1 user staff 2.7M 10 Jan 15:26 03-cookies-1.pdf-rw-r--r--@ 1 user staff 9.2M 9 Jan 16:21 Wk1_sem.pdf-rw-r--r--@ 1 user staff 502K 8 Jan 10:20 lab-01.pdf-rw-rw-rw-@ 1 user staff 2.0M 5 Jan 22:06 0410-1.wmv


Use tail command:

ls -t | tail -n 5