有没有什么简单的方法可以“按日期删除”? 在 bash 中使用“rm”-?
我今天注意到(在愉快地使用 bash 大约 8 年之后),没有使用“rm”“按日期删除”的简单方法。 因此,解决方案是围绕 rm、ls、find、awk 和 sed 等命令的组合进行管道传输。
举例来说,我想删除 2009 年以来工作目录中的每个文件,典型的方法是什么?
我想出了以下内容,这是丑陋的,只有在“rm”设置为跳过目录时才应该运行(否则你将删除父目录):
ls -la | awk '{if (substr($6,0,5)==2009) print $8}' | xargs rm
最优雅和最令人震惊的过度设计的点解决方案。
I noticed today (after ~8 years of happily hacking away at bash) that there is no trivial way to 'delete by date' using ´rm'. The solution is therefore to pipe stuff around a combination of commands like rm, ls, find, awk and sed.
Say for example I wanted to delete every file in the working directory from 2009, what would be the typical approach?
I came up with the following, which is butt-ugly and should only be run if 'rm' is set to skip over directories (otherwise you will delete the parent directory):
ls -la | awk '{if (substr($6,0,5)==2009) print $8}' | xargs rm
Points for both the most elegant and the most outrageously over-engineered solutions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我将结合 find 和 rm (不带管道)
编辑:使用您的示例的参数,这将是
警告:这仅适用于今天:-)。 (要使其每次都能工作,请将 -ctime 替换为绝对时间,请参阅联机帮助页中的 timeXY )
I would combine find and rm (without pipe)
EDIT: with parameters for your example it would be
CAVEAT: This works just today :-). (To make it work everytime, replace the -ctime with absoulte time, see timeXY in the manpage )
某些版本的 find 支持 -delete 选项,使其更加高效...
检查你的 find 手册页(这对我来说适用于最新版本的 Ubuntu)
Some versions of find support the -delete option, making it even more efficient...
Check your find man page (this has worked on most recent releases of Ubuntu for me)
我会使用:(
或
-newermt
如果你想过滤修改时间)请注意,-newerXY 的“t”形式据称允许与 cvs 兼容的任何日期格式(请参阅 doco)。
I would use:
(or
-newermt
if you want to filter on modification time)Note that the 't' form of -newerXY will allegedtly allow any date format compatible with cvs (see doco).
您应该依赖 stat(1),而不是解析 ls(1),因为 ls(1) 很容易被破坏:
例如
注意:这不会正确处理嵌入换行符的文件名。 然而,它们在野外很少被发现。
Instead of parsing ls(1) which can too easily break you should rely on stat(1):
e.g.
Note: this will not handle filenames with embedded newlines correctly. However they are rarely found in the wil.d
find(1)
比解析ls(1)
输出更有效地完成您想要的操作。编辑:需要注意的是文件名中带有空格,因此您希望有一个支持
-print0
的find
(与xargs -0
一起使用)代码>)以获得更好的性能。find(1)
is a much more efficient to do what you want than parsingls(1)
output.EDIT: something to watch for is filenames with spaces in them so you want to have a
find
which supports-print0
(to be used withxargs -0
) for better performance.