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

Linux下如何递归将各目录文件压缩至对应目录的压缩包?

解决Linux递归目录文件压缩问题

嘿,这个需求我熟!要让每个目录(包括所有子目录)都只压缩自身下的文件(不包含子文件夹),生成对应的7z/zip包,咱们可以用两种方式搞定——直接用find命令一行搞定,或者写个更灵活的shell脚本。

方法一:用find命令快速实现

7z版本

find /你的根目录路径 -type d -exec sh -c '
  target_dir="$1"
  # 只抓取当前目录下的文件,不深入子目录
  local_files=$(find "$target_dir" -maxdepth 1 -type f)
  # 只有当目录里有文件时才创建压缩包,避免空包
  if [ -n "$local_files" ]; then
    7z a -t7z "$target_dir/archive.7z" $local_files
  fi
' sh {} \;

zip版本

把上面的7z命令换成zip就行:

find /你的根目录路径 -type d -exec sh -c '
  target_dir="$1"
  local_files=$(find "$target_dir" -maxdepth 1 -type f)
  if [ -n "$local_files" ]; then
    zip "$target_dir/archive.zip" $local_files
  fi
' sh {} \;

关键参数解释:

  • -type d:让find递归找出所有目录(包括一级和所有子目录)
  • -maxdepth 1:确保只找当前目录下的文件,不会把子目录里的文件也加进去
  • -type f:只筛选文件,排除文件夹本身
  • 空包检查:避免在空目录里生成没用的压缩包

方法二:写个自定义shell脚本(更灵活)

如果想让压缩包名字和目录名一致(比如docs目录生成docs.7z),或者加更多自定义逻辑,写脚本更合适:

#!/bin/bash

# 替换成你的根目录路径
ROOT_DIR="/path/to/your/root/folder"

# 递归遍历所有目录
find "$ROOT_DIR" -type d | while read -r current_dir; do
  # 获取当前目录的名字(比如/path/to/docs → docs)
  dir_name=$(basename "$current_dir")
  # 收集当前目录下的所有文件
  local_files=$(find "$current_dir" -maxdepth 1 -type f)

  if [ -n "$local_files" ]; then
    # 用7z生成和目录同名的压缩包
    7z a -t7z "$current_dir/${dir_name}.7z" $local_files
    # 如果想用zip,注释上面一行,解开下面一行
    # zip "$current_dir/${dir_name}.zip" $local_files
  fi
done

使用步骤:

  1. 把上面的内容保存成compress_all.sh
  2. 赋予执行权限:chmod +x compress_all.sh
  3. 运行脚本:./compress_all.sh

为什么原来的脚本只在一级目录生效?

大概率是原来的脚本只遍历了一级目录(比如用for dir in */),没有递归处理子目录。而上面的方法用find -type d会自动遍历所有层级的目录,每个目录都单独执行压缩逻辑,完美解决子目录不工作的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:53:16