按字母顺序排序时删除除 N 个文件之外的所有文件的 Bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4817313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script to delete all but N files when sorted alphabetically
提问by sgtFloyd
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.zipwith YYYYMMDDbeing 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.
我有一个每天运行的 bash 脚本,用于将一个文件夹备份到一个 zip 文件中。zip 文件被命名为world YYYYMMDD.zip,并YYYYMMDD作为备份日期。我想要做的是删除除 5 个最近的备份之外的所有备份。按字母顺序对文件进行排序将首先列出最旧的文件,因此当按字母顺序排序时,我基本上需要删除除最后 5 个文件之外的所有文件。
回答by aioobe
The following line should do the trick.
以下行应该可以解决问题。
ls -F world*.zip | head -n -5 | xargs rm
ls -F: List the files alphabeticallyhead -n -5: Filter out all lines except the last 5xargs rm: remove each given file.
ls -F: 按字母顺序列出文件head -n -5: 过滤除最后 5 行以外的所有行xargs rm: 删除每个给定的文件。
回答by eumiro
How about this:
这个怎么样:
find /your/directory -name 'world*.zip' -mtime +5 | xargs rm
Test it before. This should remove all world*.zipfiles older than 5 days. So a different logic than you have.
之前测试一下。这应该删除所有world*.zip超过 5 天的文件。所以与你的逻辑不同。
回答by Ilya Kogan
I can't test it right now because I don't have a Linux machine, but I think it should be:
我现在无法测试它,因为我没有 Linux 机器,但我认为它应该是:
rm `ls -A | head -5`
回答by cledoux
ls world*.zip | sort -r | tail n+5 | xargs rm
ls world*.zip | sort -r | tail n+5 | xargs rm
sort -rwill sort in reversed order, so the newest will be at the top
sort -r将按相反顺序排序,所以最新的将在顶部
tail n+5will output lines, starting with the 5th
tail n+5将输出行,从第 5 行开始
xargs rmwill remove the files. Xargs is used to pass stdin as parameters to rm.
xargs rm将删除文件。Xargs 用于将 stdin 作为参数传递给 rm。
回答by moinudin
ls | grep ".*[\.]zip" | sort | tail -n-5 | while read file; do rm $file; done
sortsorts the filestail -n-5returns all but the 5 most recent- the
whileloop does the deleting
sort对文件进行排序tail -n-5返回除最近的 5 个之外的所有- 该
while循环是否删除

