Ubuntu – Remove all files within directory older than the most recently added ten files

command linedeletescripts

I have a compressed (tar), backup file which is added to a directory periodically. The files that are added have a naming convention like so:

JenkinsBackup_$(date +%Y%m%d-%H%M%S).tar.gz

Which results in files named like:

jenkinsBackup_20170630-091543.tar.gz

My goal is to select all files within the directory older than the most recent ten files added to the directory, and delete those files. Essentially a cleanup of the directory from command line.

Can anybody help me with the terminal commands needed to accomplish this? I'm not sure how to select and remove all files within a directory older than the most recent ten files.

Thanks in advance for any help!

Best Answer

A simple way that works fine with your file names is to use:

ls -t1 | tail -n +11 | xargs gvfs-rm
  • ls -t1 gives us a list of files based on their modification time, and newest files are first.
  • using tail -n +11 we are skipping first 10 line and getting everything else
  • then we pipe the list to xargs gvfs-rm for removal.

Note that gvfs-rm moves the file to the trash, use rm to permanently remove them.

If you want to work with the file names instead of their modification time then use ls -1r | tail -n +11 | xargs gvfs-rm instead.

A similar find solution that decides based on file names:

find -type f | sort -r | tail -n +11 | xargs gvfs-rm

or

find -type f | sort | head -n -10 | xargs gvfs-rm
Related Question