Monday 20 September 2021

Delete the last 10 files in a directory in Linux

To delete the last 10 files in a directory using a command in Linux, you can use a combination of ls, tail, xargs, and rm

ls -ltr | tail -n 10 | awk '{print $9}' | xargs rm

Breakdown of the Command:
 ls -ltr: Lists files in long format (-l), sorted by modification time, with the newest files last (-t), and in reverse order (-r).
 tail -n 10: Selects the last 10 lines from the ls output. Note that tail -n 9 would give you only 9 files; -n 10 ensures you are selecting the last 10 files.
 awk '{print $9}': Extracts the filenames from the ls output. This assumes filenames are in the 9th column. This might need adjustments based on the actual output format, especially if filenames have spaces.
 xargs rm: Passes the extracted filenames to rm for deletion.

 
 
 

 

No comments:

Post a Comment