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 → 静的サイト,ウィキ,または知識ベース)
  • Word に投稿する複数の著者

バッチ変換が必要です 単一のファイルの場合 WordToMD 簡単な選択肢です

Pandoc: バッチ変換のバックボーン

Pandoc バッチ変換の最良のツールです ファイルの任意のボリュームにスクリプトします.

Windows パワーシェルスクリプト

# 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

バッシュスクリプト (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 スクリプト

パイトン 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

フロントマターを自動的に追加する

スタティック・サイト・ジェネレーターには 前面材料が必要です 上の Python スクリプトは,基本的なフロントマターを追加します. より完全なアプローチのために,第1の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-mediaPandocはすべての画像をフォルダーに抽出します. 課題:複数の .docx ファイルが同一の名前を持つファイル (e.g., 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は,1つのファイルを処理します.
  • 500以上のファイルでは,GNU Parallelを同時処理に使用します.
find . -name "*.docx" | \
parallel pandoc {} -t gfm --wrap=none -o {.}.md

GNU Parallel をインストールする: 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ページの文書を1秒以内に変換します. 100 ファイル = 約1~2分 非常に大きな文書 (100 ページ以上) は長くかかる.

私の脚本ではコマンドが見つかりませんでした. Pandocがインストールされていることを確認してください. 走って which pandoc (macOS/Linux) または Get-Command pandoc (PowerShell) をチェックします.

パワーシェルなしで Windows で バッチ変換を実行できますか? はい 使用する .bat バッシュスクリプトを実行する Git バッシュをファイルまたはインストールします

結論

バッチ Word から Markdown への変換 Pandocとスクリプトのいくつかの行で直線です. 上記のPowerShellとBashスクリプトはほとんどのシナリオに対応します. パーソナリティ フロントマター,ディレクトリ 構造保存,画像処理では Python スクリプトが完全なコントロールを提供します. 単一の変換の場合 WordToMD 最速の選択肢です