删除除bash脚本中最新的3个文件外的所有文件 [英] Delete all files except the newest 3 in bash script
问题描述
问题:如何删除目录中除最新3个文件以外的所有文件?
Question: How do you delete all files in a directory except the newest 3?
查找最新的3个文件很简单:
Finding the newest 3 files is simple:
ls -t | head -3
但是我需要找到除最新的3个文件之外的所有文件.如何做到这一点,以及如何在同一行中删除这些文件而又不会造成不必要的for循环?
But I need to find all files except the newest 3 files. How do I do that, and how do I delete these files in the same line without making an unnecessary for loop for that?
我正在为此使用Debian Wheezy和bash脚本.
I'm using Debian Wheezy and bash scripts for this.
推荐答案
这将列出除最新三个文件以外的所有文件:
This will list all files except the newest three:
ls -t | tail -n +4
这将删除这些文件:
ls -t | tail -n +4 | xargs rm --
这还将列出点文件:
ls -At | tail -n +4
并使用dotfiles删除:
and delete with dotfiles:
ls -At | tail -n +4 | xargs rm --
但是要当心:当文件名包含换行符或空格之类的有趣字符时,解析ls
可能很危险.如果确定文件名中不包含有趣的字符,则解析ls
是非常安全的,如果是一次性脚本,则更安全.
But beware: parsing ls
can be dangerous when the filenames contain funny characters like newlines or spaces. If you are certain that your filenames do not contain funny characters then parsing ls
is quite safe, even more so if it is a one time only script.
如果您正在开发脚本以供重复使用,那么您绝对应该不解析ls
的输出,而应使用此处描述的方法: http://mywiki.wooledge.org/ParsingLs
If you are developing a script for repeated use then you should most certainly not parse the output of ls
and use the methods described here: http://mywiki.wooledge.org/ParsingLs
这篇关于删除除bash脚本中最新的3个文件外的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!