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

如何遍历指定层级子目录并批量处理其中文件?

目录文件处理方案

一、按指定流程遍历处理文件

你可以编写Shell脚本,按照「先处理每个div下所有subdiv的up1目录,再处理up2目录」的顺序批量操作文件。将以下脚本保存为process_files.sh,在root目录下执行即可:

#!/bin/bash

# 切换到root目录(替换为你的实际root路径)
cd /path/to/root || exit 1

# 遍历所有div开头的目录
for div_dir in div*; do
  # 确认是目录才继续
  [ -d "$div_dir" ] || continue

  # 遍历当前div下的所有subdiv目录
  for subdiv_dir in "$div_dir"/subdiv*; do
    [ -d "$subdiv_dir" ] || continue

    # 优先处理up1目录
    up1_path="$subdiv_dir"/up1
    if [ -d "$up1_path" ]; then
      echo "===== 正在处理目录: $up1_path ====="
      # 列出目录下的文件
      ls "$up1_path"
      # 遍历文件执行自定义操作
      for file in "$up1_path"/*.file; do
        [ -f "$file" ] || continue
        echo "处理文件: $file"
        # 在这里添加你的处理命令,例如:
        # cp "$file" /target/directory/
        # sed -i 's/old/new/g' "$file"
      done
    fi

    # 处理完up1后处理up2目录
    up2_path="$subdiv_dir"/up2
    if [ -d "$up2_path" ]; then
      echo -e "\n===== 正在处理目录: $up2_path ====="
      ls "$up2_path"
      for file in "$up2_path"/*.file; do
        [ -f "$file" ] || continue
        echo "处理文件: $file"
        # 执行你的处理操作
      done
    fi
  done
done

脚本说明:

  • 脚本会自动按div1→div2→div3的顺序遍历,每个div下先处理所有subdiv里的up1,再处理up2;
  • 替换/path/to/root为实际的root目录路径,在「处理文件」区块添加你的具体操作命令即可;
  • || exit 1用于防止切换目录失败后继续执行,避免错误操作。

二、列出单个子目录下的所有文件

如果只需要列出某一个具体子目录下的文件,直接使用ls命令:

# 列出div1/subdiv1/up1下的所有文件
ls /path/to/root/div1/subdiv1/up1

如果需要递归列出该目录下所有层级的文件(包括子目录中的文件),添加-R参数:

ls -R /path/to/root/div1/subdiv1/up1

如果只想列出文件(排除目录),使用find命令:

find /path/to/root/div1/subdiv1/up1 -type f

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 05:49:50