You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何递归列出含完整路径、大小、访问及修改时间的文件?

嘿,这需求我熟!要递归列出指定目录下特定文件的完整路径、大小、最后访问日期和最后修改日期,用find配合stat或者ls就能轻松实现,给你几个靠谱的方案:

方案1:find + stat(推荐,格式高度可控)

这个组合能精准输出你要的字段,还能自定义格式,适配大多数Linux系统:

find /opt/sas/data/vaa_oadm/sasdata -type f -name '*.sas7bdat' -exec stat -c "%n %s %x %y" {} \; | awk '{
    # 把字节大小转换成易读的GB/MB/KB/B格式
    size=$2;
    if (size >= 1024^3) size=sprintf("%.1fGB", size/(1024^3));
    else if (size >= 1024^2) size=sprintf("%.1fMB", size/(1024^2));
    else if (size >= 1024) size=sprintf("%.1fKB", size/1024);
    else size=sprintf("%dB", size);
    
    # 把默认日期格式转换成ddMMMyyyy(如10Jan2020)
    access_date=strftime("%d%b%Y", mktime(substr($3,1,4)" "substr($3,6,2)" "substr($3,9,2)" "substr($3,12,2)" "substr($3,15,2)" "substr($3,18,2)));
    modify_date=strftime("%d%b%Y", mktime(substr($4,1,4)" "substr($4,6,2)" "substr($4,9,2)" "substr($4,12,2)" "substr($4,15,2)" "substr($4,18,2)));
    
    # 按预期格式输出
    printf "%s %s %s %s\n", $1, size, access_date, modify_date;
}'

命令说明:

  • find:递归查找目标目录下的.sas7bdat文件
  • stat -c "%n %s %x %y":输出每个文件的完整路径(%n)、字节大小(%s)、最后访问时间(%x)、最后修改时间(%y)
  • awk脚本:负责把字节数转换成易读单位,同时将日期格式调整为你需要的ddMMMyyyy样式
方案2:find + ls(更简洁,适合快速场景)

如果你的系统ls支持--full-time参数,可以用这个更短的命令:

find /opt/sas/data/vaa_oadm/sasdata -type f -name '*.sas7bdat' -exec ls -lht --full-time {} \; | awk '{
    path=$9;
    size=$5;
    access_date=strftime("%d%b%Y", mktime(substr($6,1,4)" "substr($6,6,2)" "substr($6,9,2)));
    modify_date=strftime("%d%b%Y", mktime(substr($8,1,4)" "substr($8,6,2)" "substr($8,9,2)));
    printf "%s %s %s %s\n", path, size, access_date, modify_date;
}'

命令说明:

  • ls -lht --full-time:输出文件的易读大小、完整时间戳等信息
  • awk:提取路径、大小字段,并将日期格式转换为目标样式
适配macOS(BSD环境)的版本

如果是在macOS上,stat的参数格式不同,用这个调整后的命令:

find /opt/sas/data/vaa_oadm/sasdata -type f -name '*.sas7bdat' -exec stat -f "%N %z %a %m" {} \; | awk '{
    size=$2;
    if (size >= 1024^3) size=sprintf("%.1fGB", size/(1024^3));
    else if (size >= 1024^2) size=sprintf("%.1fMB", size/(1024^2));
    else if (size >= 1024) size=sprintf("%.1fKB", size/1024);
    else size=sprintf("%dB", size);
    
    access_date=strftime("%d%b%Y", $3);
    modify_date=strftime("%d%b%Y", $4);
    printf "%s %s %s %s\n", $1, size, access_date, modify_date;
}'

差异说明:

BSD版本的stat用-f指定输出格式,%a和%m直接返回时间戳,无需额外解析时间字符串。

内容的提问来源于stack exchange,提问作者athresh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:17:29