Shell脚本对文件进行计数,然后删除最旧的文件 [英] Shell script to count files, then remove oldest files

查看:245
本文介绍了Shell脚本对文件进行计数,然后删除最旧的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Shell脚本的新手,因此在这里需要一些帮助.我有一个充满备份的目录.如果我有10个以上的备份文件,我想删除最旧的文件,以便仅剩下10个最新的备份文件.

I am new to shell scripting, so I need some help here. I have a directory that fills up with backups. If I have more than 10 backup files, I would like to remove the oldest files, so that the 10 newest backup files are the only ones that are left.

到目前为止,我知道如何对文件进行计数,这似乎很容易,但是如果计数超过10,该如何删除最旧的文件?

So far, I know how to count the files, which seems easy enough, but how do I then remove the oldest files, if the count is over 10?

if [ls /backups | wc -l > 10]
    then
        echo "More than 10"
fi

推荐答案

尝试一下:

ls -t | sed -e '1,10d' | xargs -d '\n' rm

这应该处理文件名中的所有字符(换行符除外).

This should handle all characters (except newlines) in a file name.

这是怎么回事?

  • ls -t以修改时间的降序列出当前目录中的所有文件.即,最近修改的文件是第一个,每行一个文件名.
  • sed -e '1,10d'删除前10行,即10个最新文件.我用它代替tail,因为我永远不记得需要tail -n +10还是tail -n +11.
  • xargs -d '\n' rm收集每行输入(不包含换行符),并将每行作为参数传递给rm.
  • ls -t lists all files in the current directory in decreasing order of modification time. Ie, the most recently modified files are first, one file name per line.
  • sed -e '1,10d' deletes the first 10 lines, ie, the 10 newest files. I use this instead of tail because I can never remember whether I need tail -n +10 or tail -n +11.
  • xargs -d '\n' rm collects each input line (without the terminating newline) and passes each line as an argument to rm.

与任何此类物品一样,请在安全的地方进行实验.

As with anything of this sort, please experiment in a safe place.

这篇关于Shell脚本对文件进行计数,然后删除最旧的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆