本文目录导读:

- 方法1:使用系统命令(最简单)
- 方法2:Python脚本(跨平台)
- 方法3:PowerShell脚本(Windows)
- 方法4:Bash脚本(Linux/Mac/Windows Git Bash)
- 方法5:批处理脚本(Windows)
- 实用技巧
方法1:使用系统命令(最简单)
Windows (CMD/PowerShell)
# 仅复制目录结构(不包含文件) xcopy source_path target_path /t /e # 例子:复制 D:\projects 的结构到 E:\backup xcopy D:\projects E:\backup /t /e
Linux/Mac
# 复制目录结构(包含空目录) cp -r --parents source/path/ target/path/ # 或使用rsync rsync -av --include='*/' --exclude='*' source/path/ target/path/
方法2:Python脚本(跨平台)
import os
import shutil
def copy_directory_tree(src, dst):
"""复制目录树结构(不复制文件)"""
for root, dirs, files in os.walk(src):
# 计算相对路径
rel_path = os.path.relpath(root, src)
if rel_path == '.':
continue
# 创建目标路径
target_dir = os.path.join(dst, rel_path)
# 创建目录(如果不存在)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
print(f"Created: {target_dir}")
# 使用示例
src_path = "source_directory"
dst_path = "target_directory"
copy_directory_tree(src_path, dst_path)
方法3:PowerShell脚本(Windows)
# 简单版:仅复制空目录结构
Get-ChildItem -Path "C:\source" -Recurse -Directory |
ForEach-Object {
$newPath = Join-Path "C:\target" $_.FullName.Substring("C:\source".Length)
New-Item -Path $newPath -ItemType Directory -Force
}
# 增强版:可选择复制文件与否
function Copy-DirectoryTree {
param(
[string]$source,
[string]$destination,
[switch]$includeFiles
)
if ($includeFiles) {
# 复制所有内容
Copy-Item -Path $source -Destination $destination -Recurse -Container
} else {
# 仅复制目录结构
Get-ChildItem -Path $source -Recurse -Directory |
ForEach-Object {
$newPath = $_.FullName.Replace($source, $destination)
New-Item -Path $newPath -ItemType Directory -Force | Out-Null
}
}
}
# 使用
Copy-DirectoryTree -source "C:\source" -destination "C:\target"
方法4:Bash脚本(Linux/Mac/Windows Git Bash)
#!/bin/bash
# 复制目录树结构(仅目录)
copy_tree_structure() {
local src="$1"
local dst="$2"
# 使用find命令查找所有目录
find "$src" -type d -not -path "$src" | while read dir; do
# 创建对应的目标目录
local rel_path="${dir#$src}"
mkdir -p "${dst}${rel_path}"
echo "Created: ${dst}${rel_path}"
done
}
# 使用
copy_tree_structure "/path/to/source" "/path/to/destination"
方法5:批处理脚本(Windows)
@echo off
setlocal enabledelayedexpansion
REM 复制目录树结构
set SOURCE=C:\source
set DEST=C:\target
REM 使用dir命令获取目录列表
for /r "%SOURCE%" /d %%d in (*) do (
REM 获取相对路径
set "fullpath=%%d"
set "relpath=!fullpath:%SOURCE%=!"
if not "!relpath!"=="" (
mkdir "%DEST%!relpath!" 2>nul
echo Created: %DEST%!relpath!
)
)
echo 目录树复制完成!
pause
实用技巧
生成目录树文本文件
# Linux/Mac tree -d > directory_tree.txt # Windows (图形化,需先安装tree命令) tree /f > directory_tree.txt
排除特定目录
# Linux/Mac - 排除node_modules和.git
find . -type d -not -path './node_modules/*' -not -path './.git/*' | while read dir; do
mkdir -p "../backup/$dir"
done
带权限的复制
# Linux/Mac - 保留权限 cp -rp --parents source/ target/
选择建议:
- 临时使用:系统自带命令(xcopy/cp)
- 跨平台:Python脚本
- 复杂需求:Shell脚本
- Windows环境:PowerShell脚本
这些方法都能快速复制目录树结构,选择最适合你需求的即可。