简体   繁体   English

使用Shell脚本对文件进行排序,然后删除旧文件

[英]Using shell script to sort files then delete old files

I have a folder with some normal files. 我有一个包含一些普通文件的文件夹。 I want to sort them by their modified date, keeps the latest 20 entries, and from what's left, erases anything older than 20 days. 我想按修改日期对它们进行排序,保留最新的20条记录,然后从剩下的记录中删除20天以上的所有记录。

Here is my code to delete files those are > 20 days. 这是我的代码,用于删除> 20天的文件。

#!/bin/bash
cleanup="../some path/"

find $cleanup/*gz -mtime +20 -exec rm {} \;

However, I don't know how to keep the last modified 20 files, then doing the delete. 但是,我不知道如何保留最后修改的20个文件,然后进行删除。 How to fix it please? 请如何解决?

You can filter 20 filenames out with 您可以使用过滤掉20个文件名

awk 'NR > 20' 

Full command: 完整命令:

find ...... | awk 'NR > 20' | xargs -r  rm

For example 例如

seq 30 | xargs -i echo 'file{}' | awk 'NR > 20' | xargs  -r rm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM