batch automation pandoc word markdown

Batch Convert Word to Markdown: สกริปต์สําหรับการแปลงเอกสารจํานวนมาก

วิธีการแปลง batch หลายไฟล์ Word (.docx) เป็น Markdown ทันที ครอบคลุม Pandoc สคริปต์สําหรับ Windows, macOS, และ Linux, บวกกับการอัตโนมัติ 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.

เมื่อคุณต้องการการแปลง Batch

หากคุณมี:

  • ห้องสมุดเอกสารเก่าในรูปแบบ Word
  • รายงานสัปดาห์ที่จําเป็นต้องกลายเป็นหน้า Markdown
  • โครงการการย้ายเนื้อหา (Word → เว็บไซต์สแตติก, วิกี, หรือฐานความรู้)
  • ผู้เขียนหลายคนส่งเอกสาร Word ที่ตีพิมพ์ไป Markdown

คุณต้องการการแปลงแบชช์ สําหรับไฟล์เดียว WordToMD ยังคงเป็นทางเลือกที่ง่ายที่สุด

Pandoc: การแปลง Batch Backbone

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 Script (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 สําหรับการใช้งานที่สูงสุด

ไพธอน python-docx library และ Pandoc subprocess การเข้าถึงให้การควบคุมมากขึ้น

#!/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 ที่อยู่ข้างบนเพิ่มเติมข้อความเบื้องต้น สําหรับวิธีการที่ครบถ้วนกว่านี้ ค้นหาหัวข้อเอกสารจากหัวข้อ 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 เรียกเพื่อใช้ชื่อที่ถูกลอก

การอนุรักษ์โครงสร้าง Directory

เมื่อแปลงโครงสร้างโฟลเดอร์ที่ตั้งเนสต์ การรักษาระดับชั้น:

# 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

การจัดการภาพในการแปลง Batch

ด้วย --extract-media, Pandoc ถอดภาพทั้งหมดเข้าในโฟลเดอร์ ความท้าทาย: ไฟล์ .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 ประมวลผลไฟล์หนึ่งต่อการเรียก นี้เป็นเรื่องดีสําหรับถึง ~ 100 ไฟล์
  • สําหรับไฟล์ 500+ ใช้ GNU Parallel สําหรับการประมวลผลพร้อมกัน:
find . -name "*.docx" | \
parallel pandoc {} -t gfm --wrap=none -o {.}.md

ติดตั้ง GNU Parallel: brew install parallel / sudo apt install parallel

การยืนยันคุณภาพผลิต

หลังการแปลง Batch ตรวจสอบผลิตของคุณ:

  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 ก่อน คุณสมบัติของเวิร์ด แมคโรสามารถบันทึก Batch ได้: เครื่องมือ → แมคโร → ใช้ SaveAs แมคโรในไฟล์ที่เปิดทั้งหมด LibreOffice ยังสามารถแปลง Batch ผ่านเส้นคําสั่งได้: soffice --headless --convert-to docx *.doc.

การแปลงแบชช์ใช้เวลาเท่าไหร่? Pandoc เปลี่ยนแปลงเอกสาร 10 หน้าทั่วไปในเวลาไม่เกิน 1 วินาที แฟลล์ 100 รายการ = ประมาณ 1-2 นาที เอกสารขนาดใหญ่มาก (100 หน้าขึ้นไป) ใช้เวลามากกว่านี้

ผมได้รับคําสั่งที่ไม่พบในสกริปของผม ให้แน่ใจว่า Pandoc ถูกติดตั้งและติด PATH ของคุณ วิ่ง which pandoc (macOS/Linux) หรือ Get-Command pandoc (PowerShell) เพื่อตรวจสอบ

ผมสามารถทําการแปลง Batch ใน Windows โดยไม่ต้องใช้ PowerShell ได้หรือไม่? ใช่ ใช้ a .bat ไฟล์หรือติดตั้ง Git Bash เพื่อทํางาน bash script

การสรุป

การแปลง Batch Word เป็น Markdown เป็นเรื่องตรงๆ กับ Pandoc และสกริปป์ PowerShell และ Bash สกริปด้านบนจะจัดการกับฉากส่วนใหญ่ สําหรับหน้าหน้าที่กําหนดเอง การอนุรักษ์โครงสร้างประวัติ หรือการจัดการภาพ สกิปต์ Python ให้การควบคุมอย่างเต็มที่ สําหรับการแปลงครั้งเดียว WordToMD ยังคงเป็นทางเลือกที่เร็วที่สุด