batch automation pandoc word markdown

將 Word 批次轉換為 Markdown:批次文件轉換指令碼

如何一次性將多個 Word (.docx) 檔案批次轉換為 Markdown。涵蓋適用於 Windows、macOS 和 Linux 的 Pandoc 指令碼,以及用於高階用例的 Python 自動化。

W
WordToMD 團隊
·

將單個 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

驗證輸出質量

批次轉換後,抽查您的輸出:

  1. 隨機樣本 — 開啟 5-10 個轉換後的檔案並與原始檔案進行比較
  2. 桌子數量 — 計算文件中的表格並驗證它們全部已轉換
  3. 標題級別 — 確保保留標題層次結構
  4. 損壞的連結 — 搜尋 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 指令碼。

結論

批次 Word 到 Markdown 轉換 使用 Pandoc 和幾行指令碼就很簡單。上面的 PowerShell 和 Bash 指令碼可以處理大多數情況。對於自定義 frontmatter、目錄結構儲存或影像處理,Python 指令碼為您提供完全控制。對於一次性轉換, WordToMD 仍然是最快的選項。