Bash script to delete all but N files when sorted alphabetically

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

I can't test it right now because I don't have a Linux machine, but I think it should be:

rm `ls -A | head -5`

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.

Tags:

Linux

Bash

Ubuntu