以下任務要怎麼快又有效的完成呢?
把一堆M$ office的doc、docx檔轉成.md檔,好讓我可以把以前累積的文章刊登在hugo站點上,不只如此,為了方便將來管理檔案,我還要求每一個.md檔都要命名為index.md並且各自放在與原來檔名相同的資料夾內。再來,我還要在每篇文章前面加入.yaml的front matter,好讓我可以在網站上顯示相關資訊,而且原本的doc、docx檔之檔名最前面有8個數字代表日期,前4碼代表年份,第5、6碼代表月份,第7、8碼是日,有辨法自動辨視這些資訊自動帶入.yaml的front matter內的date一行內嗎?最後擷取文章內容的前100個字放進front matter 的description 內,還要建立可以看轉檔過程的報告。
我描述的很詳細,連我自己都快看花了,Chat GPT還是能明白我要的是什麼,她整理如下:
-
將
.doc
和.docx
轉成.md
-
每個
.md
命名為index.md
-
每個
.md
檔放進一個以原始檔名命名的資料夾(不含副檔名) -
每個
.md
檔前面加上固定的 front matter: -
.doc
/.docx
檔案檔名前 8 碼為日期資訊(如:20240525-信仰筆記.docx
):2024
➜ 年05
➜ 月25
➜ 日- 組成
2024-05-25T00:00:00+08:00
-
從轉出來的
.md
內文抓出前 100 個字元(中文或英數字),自動加進description:
欄位中 -
記錄轉換日誌到
convert.log
這麼多的要求,不知是否有GUI介面的軟體可以辨到?先不管了,終端機做得到!AI她要我先安裝二套軟體,其中一套叫pandoc
。在Linux之下要安裝軟體很方便,除非特殊需求,不然不用上網找來找去,只要在終端機用套作管理員APT下載安裝即可。
先輸入
sudo apt install pandoc
然後寫一個shell腳本,命名為doc-md.sh
#!/bin/bash
mkdir -p output
logfile="convert.log"
echo "==== 轉換開始:$(date) ====" > "$logfile"
for file in *.docx *.doc; do
filename=$(basename "$file")
base="${filename%.*}"
# 檢查檔名前8碼是否為日期
if [[ ! "$base" =~ ^[0-9]{8} ]]; then
echo "[ERROR] 檔名不含有效日期(YYYYMMDD):$file" | tee -a "$logfile"
continue
fi
# 擷取日期
year=${base:0:4}
month=${base:4:2}
day=${base:6:2}
hugo_date="${year}-${month}-${day}T00:00:00+08:00"
# 驗證日期
if ! date -d "$hugo_date" &>/dev/null; then
echo "[ERROR] 無效日期,略過:$file" | tee -a "$logfile"
continue
fi
folder="output/$base"
mkdir -p "$folder"
# 若為 .doc,轉為 .docx
if [[ "$file" == *.doc ]]; then
libreoffice --headless --convert-to docx "$file" --outdir . 2>/dev/null
file="${base}.docx"
fi
# 用 pandoc 轉成 markdown
temp_md="$folder/temp.md"
pandoc "$file" -f docx -t markdown -o "$temp_md"
# 強制確認 UTF-8 格式
iconv -f UTF-8 -t UTF-8 "$temp_md" -o "$temp_md" 2>/dev/null
# 擷取內文前 100 字當 description
desc=$(sed 's/^[[:space:]]*//;s/[[:space:]]*$//' "$temp_md" | tr -d '\n' | cut -c1-100)
desc_clean=$(echo "$desc" | iconv -f utf-8 -t utf-8 -c)
# 建立 index.md,寫入 front matter,確保 UTF-8 無錯碼
output_md="$folder/index.md"
printf "%s\n" \
"---" \
"date: '$hugo_date'" \
"draft: false" \
"title: \"$(echo "$base" | iconv -f utf-8 -t utf-8 -c)\"" \
"description: \"$desc_clean\"" \
"featured_image: \"\"" \
"images: [\"\"]" \
"tags: [\"\"]" \
"categories: \"信仰戳記\"" \
"---" \
"" > "$output_md"
# 加入 markdown 內文
cat "$temp_md" >> "$output_md"
rm "$temp_md"
echo "[INFO] 完成轉換:$file ➜ $output_md" | tee -a "$logfile"
done
echo "==== 轉換結束:$(date) ====" >> "$logfile"
```
再來在把這shell放在選定要執行的資料夾內後開啟終端機,然後給這個shell有被執行的權限,輸入
chmod +x doc-md.sh
最後,神奇的一刻來了,執行shell就對了!輸入
./doc-md.sh
中間雖然遇到了字體轉換的問題,但AI一下子就解決,事就這麼成了!終端機真的很神奇!搭配很懂自己的AI,可以寫出一鍵完成一堆複雜指令的腳本來完成我要求好多的轉檔任務,而且檔案容量很輕巧,23個.md檔案才171kb,相較之下,一個M$word檔足足有40kb左右。
Last modified on 2025-05-26