怎样用脚本批量修改文件扩展名?

wen 实用脚本 2

本文目录导读:

怎样用脚本批量修改文件扩展名?

  1. Windows PowerShell 脚本
  2. Windows 批处理脚本 (.bat)
  3. Linux/Mac 终端命令
  4. Python 脚本(跨平台)
  5. 高级 PowerShell 脚本(含错误处理)
  6. 使用建议
  7. 注意事项

Windows PowerShell 脚本

# 批量修改文件扩展名
# 将当前目录下所有 .txt 文件改为 .md
Get-ChildItem -Path "C:\你的文件夹路径" -Filter "*.txt" | 
ForEach-Object {
    $newName = $_.BaseName + ".md"
    Rename-Item -Path $_.FullName -NewName $newName
    Write-Host "已修改: $($_.Name) -> $newName"
}

更灵活的版本

# 可自定义源扩展名和目标扩展名
$sourcePath = "C:\你的文件夹路径"
$oldExtension = ".txt"
$newExtension = ".md"
Get-ChildItem -Path $sourcePath -Filter "*$oldExtension" | 
ForEach-Object {
    $newName = $_.BaseName + $newExtension
    Rename-Item -Path $_.FullName -NewName $newName
}

Windows 批处理脚本 (.bat)

@echo off
setlocal enabledelayedexpansion
:: 设置文件夹路径
set "folder=C:\你的文件夹路径"
:: 旧扩展名
set "oldExt=.txt"
:: 新扩展名
set "newExt=.md"
cd /d "%folder%"
for %%f in (*%oldExt%) do (
    set "filename=%%~nf"
    ren "%%f" "!filename!%newExt%"
    echo 已修改: %%f ^-> !filename!%newExt%
)
echo 修改完成!
pause

Linux/Mac 终端命令

# 将当前目录所有 .txt 改为 .md
for file in *.txt; do
    mv "$file" "${file%.txt}.md"
done
# 一行命令版本
for f in *.txt; do mv "$f" "${f%.txt}.md"; done
# 使用 rename 命令(更简单)
rename 's/\.txt$/.md/' *.txt

Python 脚本(跨平台)

import os
import glob
# 设置参数
folder_path = r"C:\你的文件夹路径"
old_ext = ".txt"
new_ext = ".md"
# 切换到目标文件夹
os.chdir(folder_path)
# 查找所有匹配的文件
for file in glob.glob(f"*{old_ext}"):
    # 分离文件名和扩展名
    filename = os.path.splitext(file)[0]
    new_filename = filename + new_ext
    # 重命名文件
    os.rename(file, new_filename)
    print(f"已修改: {file} -> {new_filename}")
print("修改完成!")

高级 PowerShell 脚本(含错误处理)

function Batch-RenameExtension {
    param(
        [string]$Path = ".",
        [string]$OldExtension,
        [string]$NewExtension,
        [switch]$Recurse
    )
    $files = Get-ChildItem -Path $Path -Filter "*$OldExtension" -Recurse:$Recurse
    foreach ($file in $files) {
        try {
            $newName = $file.BaseName + $NewExtension
            Rename-Item -Path $file.FullName -NewName $newName -ErrorAction Stop
            Write-Host "✓ 已修改: $($file.Name) -> $newName" -ForegroundColor Green
        }
        catch {
            Write-Host "✗ 修改失败: $($file.Name) - $($_.Exception.Message)" -ForegroundColor Red
        }
    }
}
# 使用示例
Batch-RenameExtension -Path "C:\你的文件夹路径" -OldExtension ".txt" -NewExtension ".md"

使用建议

  1. 重要文件先备份,或先在测试文件夹试用
  2. 指定完整路径,避免误操作
  3. 可以先使用 -WhatIf 参数预览效果(PowerShell)

注意事项

  • 确保目标新扩展名不会覆盖已有文件
  • 文件名中的特殊字符可能会造成问题
  • 对于系统文件要格外小心

选择适合你操作系统的脚本,修改其中的文件夹路径和扩展名即可使用。

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