Mengkonversi dokumen tunggal Word ke Markdown membutuhkan waktu beberapa detik dengan 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 bulk Word ke Markdown konversi.
Ketika Anda Membutuhkan Konversi Batch
Jika Anda memiliki:
- Perpustakaan dokumentasi lama dalam format Word
- Laporan mingguan yang perlu menjadi halaman Markdown
- Proyek migrasi konten (Word → situs statis, wiki, atau basis pengetahuan)
- Beberapa penulis mengirimkan Word dokumen yang dipublikasikan ke Markdown
Kau butuh konversi batch. Untuk file tunggal, WordToMD tetap menjadi pilihan termudah.
Pandoc: Backbone Konversi Batch
Pandoc adalah alat terbaik untuk konversi batch. Instal sekali, lalu skrip untuk volume file apa pun.
Skrip 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."
Jalankan:
.\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."
Jalankan:
chmod +x convert-all.sh
./convert-all.sh
Skrip Python untuk Kasus Penggunaan Lanjutan
Pythons python-docx library dan Pandoc subprocess memberikan lebih banyak kontrol:
#!/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()
Jalankan:
python3 batch_convert.py
Menambahkan Frontmatter Secara Otomatis
Generator situs statis membutuhkan materi depan. Skrip Python di atas menambahkan frontmatter dasar. Untuk pendekatan yang lebih lengkap, ekstrak judul dokumen dari judul H1 pertama:
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"
Lalu update add_frontmatter Panggilan untuk menggunakan judul yang diekstraksi.
Mempertahankan Struktur Direktori
Saat mengkonversi struktur folder yang tertanam, pertahankan hierarki:
# 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
Penanganan gambar dalam konversi batch
Dengan --extract-media, Pandoc mengekstrak semua gambar ke folder. Tantangan: beberapa file .docx dapat menghasilkan file dengan nama yang sama (e.g., image1.png)). Gunakan subdirektori per-dokumen:
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
Kinerja untuk Set Besar
Untuk set dokumen besar (100+ file):
- Pandoc memproses satu file per invocation ini baik-baik saja untuk hingga ~ 100 file
- Untuk 500+ file, gunakan GNU Parallel untuk pemrosesan bersamaan:
find . -name "*.docx" | \
parallel pandoc {} -t gfm --wrap=none -o {.}.md
Install GNU Parallel: brew install parallel / sudo apt install parallel
Validasi Kualitas Output
Setelah konversi batch, periksa output Anda:
- Sampel acak Buka 5-10 file yang dikonversi dan bandingkan dengan yang asli
- Jumlah tabel Menghitung tabel dalam dokumen dan memverifikasi mereka semua dikonversi
- Tingkat head Memastikan hierarki judul dipertahankan
- Tautan yang rusak Cari tautan Markdown dan periksa apakah mereka dapat diselesaikan
Sebuah script cek sederhana:
# 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
Bisakah saya mengonversi file .doc secara batch (format Word lama)?
Simpan mereka sebagai .docx pertama. Fitur makro Words dapat batch-save: Tools → Macros → menjalankan makro SaveAs di semua file terbuka. LibreOffice juga dapat batch-convert melalui baris perintah: soffice --headless --convert-to docx *.doc.
Berapa lama waktu yang dibutuhkan untuk mengubah batch? Pandoc mengkonversi dokumen 10 halaman dalam waktu kurang dari satu detik. 100 file = sekitar 1-2 menit. Dokumen yang sangat besar (100+ halaman) membutuhkan waktu lebih lama.
Aku mendapatkan pandoc: perintah tidak ditemukan dalam skrip saya.
Pastikan Pandoc dipasang dan pada PATH Anda. Berlarilah ! which pandoc (macOS/Linux) atau Get-Command pandoc (PowerShell) untuk memeriksa.
Bisakah saya menjalankan konversi batch di Windows tanpa PowerShell?
Ya gunakan a .bat file atau menginstal Git Bash untuk menjalankan skrip bash.
Panduan terkait
- Pandoc Word sampai Markdown Referensi lengkap Pandoc
- Word ke Static Site Generator Penerbitan konten yang dikonversi
- Word sampai GitBook Migrasi ke GitBook
Kesimpulan
Batch Word ke Markdown konversi adalah mudah dengan Pandoc dan beberapa baris skrip. Skrip PowerShell dan Bash di atas menangani sebagian besar skenario. Untuk frontmatter kustom, pemeliharaan struktur direktori, atau penanganan gambar, skrip Python memberi Anda kontrol penuh. Untuk konversi satu kali, WordToMD tetap pilihan tercepat.