batch automation pandoc word markdown

Word를 Markdown로 배치 변환: 대량 문서 변환용 스크립트

여러 Word (.docx) 파일을 Markdown로 한 번에 대량 변환하는 방법. Windows, macOS 및 Linux용 Pandoc 스크립트를 포함하고, 고급 사용 사례를 위한 파이썬 자동화를 포함합니다.

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에 게시하는 Markdown 문서를 제출하고 있습니다.

배치 변환이 필요합니다. 단일 파일의 경우 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-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

자동으로 전두머리를 추가

정적 사이트 생성기는 전면 물질을 필요로 합니다. 위의 파이썬 스크립트는 기본적인 프론트마터를 추가합니다. 보다 완전한 접근을 위해, 첫 번째 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 파일은 동일한 이름의 파일을 생성할 수 있습니다 (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 병렬을 설치합니다: 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 매크로를 실행합니다. 리브레오피스는 또한 명령줄을 통해 배치 변환을 할 수 있습니다: soffice --headless --convert-to docx *.doc.

배치 변환은 얼마나 걸리나요? Pandoc는 일반적인 10페이지의 문서를 초 안에 변환합니다. 100개의 파일은 대략 1-2분입니다. 매우 큰 문서 (100 페이지 이상) 는 더 오래 걸립니다.

pandoc: 내 스크립트에서 명령이 발견되지 않았습니다. Pandoc가 설치되어 있고 PATH에 있는지 확인하십시오. 도망쳐! which pandoc (macOS/Linux) 또는 Get-Command pandoc (PowerShell) 확인하기 위해.

파워 셸 없이 윈도우에서 배치 변환을 실행할 수 있나요? 예 사용 a .bat Bash 스크립트를 실행하기 위해 Git Bash를 파일하거나 설치합니다.

결론

배치 Word로 Markdown 변환 Pandoc와 몇 줄의 스크립트를 통해 간단합니다. 위의 PowerShell 및 Bash 스크립트는 대부분의 시나리오를 처리합니다. 사용자 정의 프론트메터, 디렉터리 구조 보존 또는 이미지 처리, 파이썬 스크립트는 당신에게 완전한 통제를 제공합니다. 일회용 변환에 있어서 WordToMD 여전히 가장 빠른 선택입니다.