将单个 Word 文档转换为 Markdown 只需几秒钟 WordToMD. But what if you have 50, 100, or 500 .docx files to convert? That’s where batch conversion scripts come in. This guide covers the fastest approaches for 批量 Word 到 Markdown 转换.
当您需要批量转换时
如果您有:
- Word 格式的遗留文档库
- 需要变成 Markdown 页面的周报
- 内容迁移项目(Word → 静态站点、wiki 或知识库)
- 多个作者提交发布到 Markdown 的 Word 文档
您需要批量转换。对于单个文件, WordToMD 仍然是最简单的选择。
Pandoc:批量转换主干
Pandoc 是批量转换的最佳工具。安装一次,然后为任意文件卷编写脚本。
Windows PowerShell 脚本
# convert-all.ps1
# Converts all .docx files in current directory to .md
$docxFiles = Get-ChildItem -Path "." -Filter "*.docx" -Recurse
foreach ($file in $docxFiles) {
$outputPath = [System.IO.Path]::ChangeExtension($file.FullName, ".md")
pandoc `
$file.FullName `
-t gfm `
--wrap=none `
--extract-media="./media" `
-o $outputPath
Write-Host "✓ $($file.Name) → $([System.IO.Path]::GetFileName($outputPath))"
}
Write-Host "Done. Converted $($docxFiles.Count) files."
运行它:
.\convert-all.ps1
Bash 脚本(macOS / Linux)
#!/bin/bash
# convert-all.sh
# Converts all .docx files recursively
OUTPUT_DIR="./markdown-output"
mkdir -p "$OUTPUT_DIR"
find . -name "*.docx" | while read -r docx_file; do
filename=$(basename "$docx_file" .docx)
output="$OUTPUT_DIR/$filename.md"
pandoc \
"$docx_file" \
-t gfm \
--wrap=none \
--extract-media="$OUTPUT_DIR/media" \
-o "$output"
echo "✓ $docx_file → $output"
done
echo "Done."
运行它:
chmod +x convert-all.sh
./convert-all.sh
Python Script for Advanced Use Cases
Python 的 python-docx 库和 Pandoc 子进程方法提供了更多控制:
#!/usr/bin/env python3
"""
batch_convert.py — Convert all .docx files to Markdown with frontmatter injection
"""
import os
import subprocess
import sys
from pathlib import Path
from datetime import datetime
INPUT_DIR = Path("./word-docs")
OUTPUT_DIR = Path("./markdown-output")
OUTPUT_DIR.mkdir(exist_ok=True)
def convert_file(docx_path: Path) -> Path:
"""Convert a .docx file to GFM Markdown using Pandoc."""
output_path = OUTPUT_DIR / docx_path.with_suffix(".md").name
result = subprocess.run(
[
"pandoc",
str(docx_path),
"-t", "gfm",
"--wrap=none",
f"--extract-media={OUTPUT_DIR}/media",
"-o", str(output_path)
],
capture_output=True,
text=True
)
if result.returncode != 0:
print(f" ERROR: {result.stderr}", file=sys.stderr)
return None
return output_path
def add_frontmatter(md_path: Path, title: str) -> None:
"""Prepend YAML frontmatter to a Markdown file."""
frontmatter = f"""---
title: "{title}"
date: {datetime.now().strftime('%Y-%m-%d')}
draft: false
---
"""
content = md_path.read_text(encoding="utf-8")
md_path.write_text(frontmatter + content, encoding="utf-8")
def main():
docx_files = list(INPUT_DIR.glob("**/*.docx"))
if not docx_files:
print(f"No .docx files found in {INPUT_DIR}")
return
print(f"Converting {len(docx_files)} files...")
success = 0
for docx_path in docx_files:
print(f" Converting: {docx_path.name}")
output_path = convert_file(docx_path)
if output_path:
# Use filename (without extension) as title, replace hyphens/underscores
title = docx_path.stem.replace("-", " ").replace("_", " ").title()
add_frontmatter(output_path, title)
print(f" ✓ → {output_path.name}")
success += 1
else:
print(f" ✗ Failed: {docx_path.name}")
print(f"\nDone: {success}/{len(docx_files)} files converted.")
if __name__ == "__main__":
main()
运行它:
python3 batch_convert.py
自动添加 Frontmatter
静态站点生成器需要 frontmatter。上面的 Python 脚本添加了基本的 frontmatter。要获得更完整的方法,请从第一个 H1 标题中提取文档标题:
def extract_title(md_content: str) -> str:
"""Extract the first H1 heading as the title."""
for line in md_content.splitlines():
if line.startswith("# "):
return line[2:].strip()
return "Untitled"
然后更新 add_frontmatter 调用以使用提取的标题。
保留目录结构
转换嵌套文件夹结构时,维护层次结构:
# Bash: preserve subdirectory structure
find ./word-docs -name "*.docx" | while read -r docx; do
# Calculate relative path
rel_path="${docx#./word-docs/}"
output_dir="./markdown-output/$(dirname "$rel_path")"
mkdir -p "$output_dir"
output="$output_dir/$(basename "$docx" .docx).md"
pandoc "$docx" -t gfm --wrap=none -o "$output"
echo "✓ $rel_path"
done
批量转换中的图像处理
与
具有标题行和一致列的 --extract-media,Pandoc 将所有图像提取到一个文件夹中。挑战:多个 .docx 文件可能会生成具有相同名称的文件(例如, image1.png)。使用每个文档的子目录:
for docx_file in *.docx; do
slug="${docx_file%.docx}"
mkdir -p "./media/$slug"
pandoc "$docx_file" \
-t gfm \
--wrap=none \
--extract-media="./media/$slug" \
-o "$slug.md"
done
大型设备的性能
对于大型文档集(100 个以上文件):
- Pandoc 每次调用处理一个文件 — 这对于最多 100 个文件来说是可以的
- 对于 500 多个文件,使用 GNU Parallel 进行并发处理:
find . -name "*.docx" | \
parallel pandoc {} -t gfm --wrap=none -o {.}.md
安装 GNU 并行: brew install parallel / sudo apt install parallel
验证输出质量
批量转换后,抽查您的输出:
- 随机样本 — 打开 5-10 个转换后的文件并与原始文件进行比较
- 桌子数量 — 计算文档中的表格并验证它们全部已转换
- 标题级别 — 确保保留标题层次结构
- 损坏的链接 — 搜索 Markdown 链接并验证它们是否解析
一个简单的检查脚本:
# Count files with no headings (might indicate conversion failure)
for md in ./markdown-output/*.md; do
if ! grep -q "^#" "$md"; then
echo "No headings found: $md"
fi
done
FAQ
我可以批量转换 .doc 文件(旧 Word 格式)吗?
首先将它们另存为 .docx。Word 的宏功能可以批量保存:工具 → 宏 → 在所有打开的文件中运行 SaveAs 宏。LibreOffice 还可以通过命令行进行批量转换: soffice --headless --convert-to docx *.doc.
批量转换需要多长时间? Pandoc 可在一秒内转换典型的 10 页文档。100 个文件 = 大约 1-2 分钟。非常大的文档(100 多页)需要更长的时间。
我在脚本中收到“pandoc:找不到命令”。
确保 Pandoc 已安装并位于您的 PATH 中。运行 which pandoc (macOS/Linux) 或 Get-Command pandoc (PowerShell)进行检查。
我可以在不使用 PowerShell 的情况下在 Windows 上运行批量转换吗?
是 — 使用 .bat 文件或安装 Git Bash 来运行 bash 脚本。
相关指南
- Pandoc Word到 Markdown — 完整的 Pandoc 参考
- 字到静态站点生成器 — 发布转换后的内容
- Word 到 GitBook — 迁移到 GitBook
结论
批量 Word 到 Markdown 转换 使用 Pandoc 和几行脚本就很简单。上面的 PowerShell 和 Bash 脚本可以处理大多数情况。对于自定义 frontmatter、目录结构保存或图像处理,Python 脚本为您提供完全控制。对于一次性转换, WordToMD 仍然是最快的选项。