仅用find命令查找目录中修改时间最早的文件是否可行?
问题:仅用find命令查找指定目录中修改时间最早的文件及所在目录
我正在进行Linux练习,需在指定目录中查找修改时间最早的文件及其所在目录。要求仅使用find命令,不能借助管道或脚本,但尝试了如下命令仍未得到预期结果:
find archive -type f -exec stat -c "%Y %n" {} \; -print
以及
find ~/archive -type f -exec stat -c "%Y" {} +
请问是否有可行的方法?
可行方案
可以通过find的-exec选项内嵌shell命令来跟踪记录最早的文件,无需管道或独立脚本,具体命令如下:
find archive -type f -exec sh -c ' current=$(stat -c "%Y" "$1") if [ -z "$oldest_ts" ] || [ "$current" -lt "$oldest_ts" ]; then oldest_ts="$current" oldest_file="$1" fi echo "$oldest_ts $oldest_file" > /tmp/find_oldest.tmp ' _ {} \; && cat /tmp/find_oldest.tmp && rm -f /tmp/find_oldest.tmp
说明:
- 每次处理一个文件时,用
stat获取其Unix秒级修改时间戳。 - 维护两个变量:
oldest_ts记录当前找到的最早时间戳,oldest_file记录对应文件路径,每次比较后更新。 - 用临时文件保存最新结果,最后读取并清理临时文件。
如果只需要输出文件路径(不带时间戳),可以调整命令如下:
find archive -type f -exec sh -c ' current=$(stat -c "%Y" "$1") if [ -z "$oldest_ts" ] || [ "$current" -lt "$oldest_ts" ]; then oldest_ts="$current" oldest_file="$1" fi echo "$oldest_file" > /tmp/find_oldest.tmp ' _ {} \; && cat /tmp/find_oldest.tmp && rm -f /tmp/find_oldest.tmp
内容的提问来源于stack exchange,提问作者Joseph
相关产品推荐
相关产品推荐

