Master
Master

Reputation: 53

How to delete all files except last 5 ordered by date in linux bash

I have folder with big amount of logs, extension is ".log".

2020.01.03.log
2020.01.04.log
2020.01.01.log
2020.01.02.log 
do_not_remove_1.txt
2020.01.06.log
2020.01.07.log 
do_not_remove_2.txt
2020.01.05.log

I need to sort them by date and delete all log files except recent 5 log files. Also this folder contains other files, but log files are all with extension ".log", so i need to filter them, then sort, then remove all except recent 5.

i.e. i need to remove

2020.01.01.log
2020.01.02.log 

from example above.

How to do this in linux bash?

Upvotes: 1

Views: 1337

Answers (1)

Hellmar Becker
Hellmar Becker

Reputation: 2972

Start with this:

ls -tr | head -n -5

This gives you a listing of all files except the newest 5. Now pipe this into xargs:

ls -tr | head -n -5 | xargs rm -f

This is not a complete solution yet, it will likely cause problems with filenames that contain unusual characters. But you can start working from there.

Upvotes: 3

Related Questions