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
gives us a list of files based on their modification time, and newest files are first.tail -n +11
we are skipping first 10 line and getting everything elsexargs gvfs-rm
for removal.Note that
gvfs-rm
moves the file to the trash, userm
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:or