Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to delete all but N files when sorted alphabetically

Tags:

linux

bash

ubuntu

It's hard to explain in the title.

I have a bash script that runs daily to backup one folder into a zip file. The zip files are named worldYYYYMMDD.zip with YYYYMMDD being the date of backup. What I want to do is delete all but the 5 most recent backups. Sorting the files alphabetically will list the oldest ones first, so I basically need to delete all but the last 5 files when sorted in alphabetical order.

like image 431
sgtFloyd Avatar asked Jan 27 '11 14:01

sgtFloyd


2 Answers

The following line should do the trick.

ls -F world*.zip | head -n -5 | xargs -r rm
  • ls -F: List the files alphabetically
  • head -n -5: Filter out all lines except the last 5
  • xargs -r rm: remove each given file. -r: don't run rm if the input is empty
like image 186
aioobe Avatar answered Oct 03 '22 23:10

aioobe


How about this:

find /your/directory -name 'world*.zip' -mtime +5 | xargs rm

Test it before. This should remove all world*.zip files older than 5 days. So a different logic than you have.

like image 37
eumiro Avatar answered Oct 03 '22 23:10

eumiro