大多数文件系统不存储文件的创建时间,因此您能做的最好的事情就是检查文件的最后一次修改时间。
如果您有最新版本的 GNU find(例如在 Linux 或 Cygwin 上)或 FreeBSD 或 OSX,您可以直接将一个文件的日期与另一个文件的日期进行比较。此外,这些版本的 find 可以使用文件创建时间(称为它的出生时间,用 表示B
),如果它在您的系统上可用的话。替换B
为m
下面使用修改时间而不是出生时间。
find /path/to/directory -newerBt '2009-01-01' ! -newerBt '2010-01-01' -type f -delete
Run Code Online (Sandbox Code Playgroud)
无需-delete
先运行一次以确保这些是您想要的文件。上面的命令也会删除子目录中的文件;如果不需要,请-mindepth 1 -maxdepth 1
在目录名称后添加。
如果您的版本find
没有-newerXY
主要版本,则需要创建时间戳文件来标记要匹配的时间范围的边界。
touch -t 200901010000 /tmp/from
touch -t 201001010000 /tmp/to
find /path/to/directory -newer /tmp/from ! -newer /tmp/to -type f -exec rm {} +
Run Code Online (Sandbox Code Playgroud)
Zsh 的glob 限定符可以在一个时间间隔内匹配文件,但边界只能相对于当前日期(例如N天前)表示。
rm /path/to/directory/*(.m+566^m+931)
Run Code Online (Sandbox Code Playgroud)
您还可以将时间戳文件用于精确日期,但会失去简洁性。
touch -t 200901010000 /tmp/from
touch -t 201001010000 /tmp/to
rm /path/to/directory/*(.e\''[[ $REPLY -nt /tmp/from && $REPLY -ot /tmp/to ]]'\')
Run Code Online (Sandbox Code Playgroud)