脚本如何批量修改文件扩展名

wen 实用脚本 1

本文目录导读:

脚本如何批量修改文件扩展名

  1. Windows PowerShell (推荐)
  2. Windows CMD
  3. Python脚本
  4. Linux/Mac终端
  5. 批处理文件 (.bat)
  6. 使用建议

Windows PowerShell (推荐)

# 将当前目录下所有.txt文件改为.md
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '\.txt$','.md' }
# 修改特定文件夹中的文件
Get-ChildItem "C:\path\to\folder\*.jpg" | Rename-Item -NewName { $_.Name -replace '\.jpg$','.png' }

Windows CMD

# 将.jpg改为.png
ren *.jpg *.png
# 更复杂的例子(需要for循环)
for %f in (*.txt) do ren "%f" "%~nf.md"

Python脚本

import os
import glob
# 修改当前目录下所有.txt文件为.md
for file in glob.glob("*.txt"):
    base = os.path.splitext(file)[0]
    os.rename(file, base + ".md")
# 递归修改子目录
import os
for root, dirs, files in os.walk("."):
    for file in files:
        if file.endswith(".txt"):
            old_path = os.path.join(root, file)
            new_path = os.path.join(root, file[:-4] + ".md")
            os.rename(old_path, new_path)

Linux/Mac终端

# 方法1:使用rename命令
rename 's/\.txt$/.md/' *.txt
# 方法2:使用for循环
for file in *.txt; do
    mv "$file" "${file%.txt}.md"
done
# 方法3:更复杂的匹配
find . -name "*.jpg" -exec sh -c 'mv "$0" "${0%.jpg}.png"' {} \;

批处理文件 (.bat)

@echo off
setlocal enabledelayedexpansion
set "source_ext=txt"
set "target_ext=md"
for %%f in (*.%source_ext%) do (
    set "filename=%%~nf"
    ren "%%f" "!filename!.%target_ext%"
)
echo 完成!
pause

使用建议

  • Windows用户:优先使用PowerShell,功能强大
  • Mac/Linux用户:使用终端命令
  • 需要复杂逻辑:使用Python脚本
  • 简单批量修改:CMD的ren命令即可

⚠️ 注意:建议先备份文件,或在测试文件夹中先测试脚本!

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