如何用脚本快速复制文件结构

wen 实用脚本 2

本文目录导读:

如何用脚本快速复制文件结构

  1. Linux/Mac 系统
  2. Windows 系统 (PowerShell)
  3. 跨平台 Python 脚本
  4. 选择性复制结构+特定文件类型
  5. 实用技巧

Linux/Mac 系统

只复制目录结构(不包括文件)

#!/bin/bash
# 复制目录结构
find /source/directory -type d -printf "%P\0" | xargs -0 -I {} mkdir -p /target/directory/{}

简化版本

rsync -av --include='*/' --exclude='*' /source/ /target/

Windows 系统 (PowerShell)

只复制目录结构

# 复制目录结构
Get-ChildItem -Path "C:\source" -Recurse -Directory | ForEach-Object {
    $targetPath = $_.FullName.Replace("C:\source", "D:\target")
    New-Item -Path $targetPath -ItemType Directory -Force
}

使用 robocopy(推荐)

:: 只复制目录结构,不复制文件
robocopy "C:\source" "D:\target" /E /XF * /NDL /NFL /NP

跨平台 Python 脚本

import os
import shutil
def copy_directory_structure(source, target):
    for root, dirs, files in os.walk(source):
        # 计算相对路径
        relative_path = os.path.relpath(root, source)
        target_path = os.path.join(target, relative_path)
        # 创建目标目录
        os.makedirs(target_path, exist_ok=True)
# 使用示例
copy_directory_structure("/path/to/source", "/path/to/target")

选择性复制结构+特定文件类型

Linux/Mac

#!/bin/bash
# 只复制 .txt 和 .md 文件及目录结构
rsync -av --include='*/' --include='*.txt' --include='*.md' --exclude='*' /source/ /target/

Windows PowerShell

# 选择性复制
Get-ChildItem -Path "C:\source" -Recurse -Directory | ForEach-Object {
    $targetPath = $_.FullName.Replace("C:\source", "D:\target")
    New-Item -Path $targetPath -ItemType Directory -Force
}
# 复制特定文件
Copy-Item -Path "C:\source\*.txt" -Destination "D:\target" -Recurse

实用技巧

显示进度

# Linux/Mac 显示进度
rsync -av --progress --include='*/' --exclude='*' /source/ /target/

排除特定目录

# 排除 node_modules 和 .git
rsync -av --include='*/' --exclude='*' --exclude='node_modules' --exclude='.git' /source/ /target/

推荐使用 rsync(Linux/Mac)或 robocopy(Windows),因为它们支持断点续传、显示进度、排除规则等功能,适合处理大量文件和复杂目录结构。

抱歉,评论功能暂时关闭!