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

Mac终端/Python:从文件列表文本按指定深度筛选目录与文件

解决方案

终端命令(Mac BSD环境)

你之前的grep命令存在两个关键问题:

  1. 正则表达式里[^\/]仅匹配单个非斜杠字符,而目录名(比如dir1)是多字符,需用[^\/]+表示1个或多个非斜杠字符;
  2. 命令末尾缺少闭合的单引号,导致语法错误。

1. 匹配Documents下所有直接子项(含目录和文件)

grep -E 'home/Documents/[^/]+$' filelist.txt

2. 仅匹配Documents下的直接子目录(结尾带/)

grep -E 'home/Documents/[^/]+/$' filelist.txt

3. 用awk灵活控制输出

  • 只输出路径:
awk '$NF ~ /^home\/Documents\/[^\/]+\/?$/ {print $NF}' filelist.txt
  • 输出完整行:
awk '$NF ~ /^home\/Documents\/[^\/]+\/?$/' filelist.txt

Python脚本方案

如果需要后续扩展过滤逻辑,用Python处理更灵活:

with open('filelist.txt', 'r') as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        # 提取每行最后一列的路径
        path = line.split()[-1]
        # 判断是否为Documents的直接子项
        if path.startswith('home/Documents/'):
            # 去掉前缀后,剩余部分不含嵌套层级的斜杠
            relative_part = path[len('home/Documents/'):].rstrip('/')
            if '/' not in relative_part:
                # 可选:输出完整行或仅路径
                print(line)
                # print(path)

输出示例

运行后会得到符合要求的结果:

hrw-rw-r-- user1/user1       0 2024-08-15 11:00 home/Documents/dir1/
-rw-rw-r-- user1/user1    2160 2024-08-17 12:00 home/Documents/dir2/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 10:29:54