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

如何提取并格式化输出stat(2)返回的文件信息(支持多文件)

从stat(2)输出中提取通用文件信息的方法

首先,先把你提供的stat(2)输出贴出来方便参考:

File: 'testarg.txt'
Size: 8 Blocks: 1 IO Block: 121072 regular file
Device: 30h/48d Inode: 716627550 Links: 1
Access: (0644/-rw-r--r--) Uid: (74112/ laz18) Gid: (72216/grp.csci.mentors)
Access: 2018-04-29 14:56:51.380908597 -0700
Modify: 2018-04-29 14:37:51.230987592 -0700
Change: 2018-04-29 14:37:51.231987501 -0700
Birth: -

要提取这些信息且适配任意文件,我推荐两种可靠的方案——尽量避免直接解析默认的文本输出(毕竟不同系统的stat默认格式可能有差异):

方案1:用Shell命令直接格式化输出(最简单)

stat命令本身支持自定义输出格式,这比事后解析文本靠谱多了,格式稳定且适配所有文件。比如要提取文件名、大小、权限、修改时间,直接用:

stat --printf="Filename: %n\nSize: %s bytes\nPermissions: %a (%A)\nModify Time: %y\n" testarg.txt

执行后会输出清晰的结构化内容:

Filename: testarg.txt
Size: 8 bytes
Permissions: 644 (-rw-r--r--)
Modify Time: 2018-04-29 14:37:51.230987592 -0700

常用的占位符对应:

  • %n: 文件名
  • %s: 文件大小(字节)
  • %a: 八进制权限
  • %A: 人类可读的权限字符串
  • %y: 修改时间(带纳秒)
  • %u: UID,%U: 用户名
  • %g: GID,%G: 组名

如果因为某些原因必须解析默认的stat输出,也可以用grep+正则精准提取,比如:

# 提取文件名
stat testarg.txt | grep -oP "File: '\K[^']+"
# 提取大小
stat testarg.txt | grep -oP "Size: \K\d+"
# 提取权限(可读格式)
stat testarg.txt | grep -oP "Access: \(\d{4}/\K[^)]+"

方案2:用编程语言调用stat(2)系统调用(最灵活)

如果需要在程序里处理,直接调用系统提供的stat(2)接口获取结构化数据,比解析文本高效且可靠。以Python为例,用os.stat就能直接拿到所有字段:

import os
import stat
import time

def extract_file_stats(file_path):
    try:
        # 直接调用stat(2)系统调用
        stat_data = os.stat(file_path)
        # 整理成易读的字典
        return {
            '文件名': os.path.basename(file_path),
            '大小(字节)': stat_data.st_size,
            '八进制权限': oct(stat_data.st_mode)[-3:],
            '可读权限': stat.filemode(stat_data.st_mode),
            'UID': stat_data.st_uid,
            'GID': stat_data.st_gid,
            '访问时间': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(stat_data.st_atime)),
            '修改时间': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(stat_data.st_mtime)),
            '状态变更时间': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(stat_data.st_ctime))
        }
    except FileNotFoundError:
        print(f"错误:文件 {file_path} 不存在")
        return None

# 示例使用
file_info = extract_file_stats('testarg.txt')
if file_info:
    for key, value in file_info.items():
        print(f"{key}: {value}")

运行后会输出:

文件名: testarg.txt
大小(字节): 8
八进制权限: 644
可读权限: -rw-r--r--
UID: 74112
GID: 72216
访问时间: 2018-04-29 14:56:51
修改时间: 2018-04-29 14:37:51
状态变更时间: 2018-04-29 14:37:51

这种方法完全不受stat输出格式的影响,适配任何文件,还能根据需求灵活扩展提取更多字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:39:20