[英]Bash script to delete all but N files when sorted alphabetically
It's hard to explain in the title.在标题中很难解释。
I have a bash script that runs daily to backup one folder into a zip file.我有一个每天运行的 bash 脚本,用于将一个文件夹备份到一个 zip 文件中。 The zip files are named world YYYYMMDD
.zip with YYYYMMDD
being the date of backup. zip 文件被命名为world YYYYMMDD
.zip,其中YYYYMMDD
是备份日期。 What I want to do is delete all but the 5 most recent backups.我想要做的是删除除 5 个最近的备份之外的所有备份。 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.按字母顺序对文件进行排序将首先列出最旧的文件,因此当按字母顺序排序时,我基本上需要删除除最后 5 个文件之外的所有文件。
The following line should do the trick.以下行应该可以解决问题。
ls -F world*.zip | head -n -5 | xargs -r rm
ls -F
: List the files alphabetically ls -F
:按字母顺序列出文件head -n -5
: Filter out all lines except the last 5 head -n -5
: 过滤除最后 5 行以外的所有行xargs -r rm
: remove each given file. xargs -r rm
:删除每个给定的文件。 -r
: don't run rm
if the input is empty -r
: 如果输入为空,则不运行rm
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.这应该会删除所有超过 5 天的world*.zip
文件。 So a different logic than you have.所以与你的逻辑不同。
我现在无法测试它,因为我没有 Linux 机器,但我认为它应该是:
rm `ls -A | head -5`
ls | grep ".*[\.]zip" | sort | tail -n-5 | while read file; do rm $file; done
sort
sorts the files sort
对文件sort
排序tail -n-5
returns all but the 5 most recent tail -n-5
返回除最近的 5 个之外的所有内容while
loop does the deleting while
循环执行删除操作ls world*.zip | sort -r | tail n+5 | xargs rm
sort -r
will sort in reversed order, so the newest will be at the top sort -r
将按相反顺序排序,所以最新的将在顶部
tail n+5
will output lines, starting with the 5th tail n+5
将输出行,从第 5 行开始
xargs rm
will remove the files. xargs rm
将删除文件。 Xargs is used to pass stdin as parameters to rm. Xargs 用于将 stdin 作为参数传递给 rm。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.