需求:從當前目錄遞迴尋找特定 HTML 檔案,自動生成一個包含所有檔案超連結的索引頁面,方便瀏覽器單一入口存取。本文示範使用 find、while 迴圈與 vim 批次編輯的完整流程。
find . -iname "*valid*.*" > valid.txt
輸出範例:
./ValidityState-002.html
./ValidityState-customError-expected.txt
./ValidityState-customError.html
...
cat valid.txt | while read line; do
echo "$line" >> index.html
done
若中間產出為 href="./xxx.html">./xxx.html,需補全 <a> 與 </a>:
vim index.html<a href=::%s/^/<a href=/</a>::%s/$/<\/a>/cat > generate_index.sh << 'EOF'
#!/bin/bash
OUTPUT="index.html"
echo "HTML Index " > "$OUTPUT"
find . -type f -iname "*.html" | sort | while read filepath; do
# 移除開頭 ./ 並轉義 HTML 特殊字元
display="${filepath#./}"
href=$(printf '%s\n' "$display" | sed 's/&/\&/g; s/\</g; s/>/\>/g; s/"/\"/g')
echo "- $href
" >> "$OUTPUT"
done
echo "
" >> "$OUTPUT"
EOF
chmod +x generate_index.sh
./generate_index.sh
grep -oP '(?<=).*(?= )' "$filepath")。Get-ChildItem -Recurse -Filter *.html | ForEach-Object { "$($_.Name)" } | Set-Content index.html掌握 Shell 文字處理管線,能將重複手工操作轉化為可複用自動化腳本,大幅提升運維與開發效率。