我想修改文件文件的日期,以便它比目录dir中的文件更早。时差的价值并不重要,因为它的目标只是让它变老,从而使它变老。
为了做到这一点,我需要touch file的日期值大于dir中的日期值。如何在dir中恢复最老文件的日期值,并从中减去一定的时间(例如1秒)?
发布于 2019-07-17 16:00:18
您可以通过两个步骤完成此操作:复制时间戳,然后调整它以使其更老:
#find the eldest file in dir
eldest=$(ls -t dir | tail -1)
#duplicate the time
touch -r "dir/$eldest" myfile
#make the file one second older
touch -A -000001 myfile发布于 2019-07-17 16:11:20
您可以使用find's -printf或stat获得时间戳,并对它们进行排序,以获得最古老的时间戳。然后减去所需的内容,并将其用作touch的日期说明。find的缺点是打印小数秒,在计算时必须删除。
oldest=$(stat -c "%Y" dir/*|sort|head -1)
touch -d "@$((oldest-1))" dir/file
# or touch -d "@$((oldest-60))" file # subtract 1 min to see the difference in normal ls -l output.GNU支持日期语法-d @seconds-since-epoch。POSIX没有具体规定。
stat命令不是由POSIX指定的,它是GNU的一部分,参见https://stackoverflow.com/questions/27828585/posix-analog-of-coreutils-stat-command。
因此,这个解决方案应该在Linux系统上工作,但可能不适用于一般的UNIX系统。
发布于 2019-07-17 22:35:09
可移植性是,您必须使用perl来收集时间戳,减去所需的时间量,然后将其格式化为touch。
t=$(perl make-oldest 1 dir/*)
if [ "$t" -gt 0 ]
then
touch -t "$t" file
else
echo "Sorry, unable to find a file!"
fi..。最古老的perl脚本是:
#!/usr/bin/perl -w
use strict;
use POSIX qw(strftime);
my $subtract = shift;
my $oldest = 0;
for (@ARGV) {
my @s = stat;
next unless @s;
if ($oldest) {
$oldest = $s[9] if $s[9] < $oldest;
} else {
$oldest = $s[9];
}
}
if ($oldest) {
# convert ($oldest - $subtract) into CCCCYYMMDDhhmm.SS
print strftime "%Y%m%d%H%M.%S\n", localtime($oldest - $subtract);
} else {
print "0\n";
}其意图是您的shell扩展通配符dir/*以获取文件名列表。perl脚本有两个参数:从最老的文件中减去的秒数和收集时间戳的文件列表。
perl脚本取出减法参数,然后遍历给定的文件,并跟踪最古老的修改时间。如果它不能读取任何文件,那么它将返回零(正如上面的包装脚本所测试的那样)。如果找到了最老的文件,则使用strftime函数将减去的时间戳转换为touch的适当格式。
https://unix.stackexchange.com/questions/530690
复制相似问题