批量下載Markdown文件到本地

批量下載Markdown文件到本地

在Markdown 文件中 可能存在遠程引用圖片的情況,但是在某些情況下 ,我們處於無網環境, 就可能造成Markdown 查看異常

1
> [圖片](https://cn.bing.com/images/search?q=%25E5%259B%25BE%25E7%2589%2587&FORM=IQFRBA&id=31F3A37194BC03C4AD16D80C327FF51215AB2959)

此時 把遠程文件替換成本地文件即可

1
> [圖片](xxxx)

數量少的情況下可以手動下載,如果遇到數量較多的情況就需要腳本下載了

Linux 批量下載Markdown文件並批量替換

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/bin/bash

file=$1
# 獲取所有符合格式的文本行
text_lines=$(grep -oP '\!\[圖片\]\(\K[^)]+' "../$file")

# 循環處理每一行
for text_line in $text_lines; do
# 下載並保存鏈接對應的文件
filename=$RANDOM+".png"
echo "隨機數: $filename"
wget -O "$filename" "$text_line"


# 替換括號內的鏈接爲處理後的文件名
sed -i "s|$text_line|$filename|g" "../$file"
done

Win 批量下載Markdown文件並批量替換

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$file = $args[0]
# 獲取所有符合格式的文本行
$text_lines = Select-String -Path "..\$file" -Pattern '\!\[圖片\]\(\K[^)]+' | ForEach-Object { $_.Matches.Value }

# 循環處理每一行
foreach ($text_line in $text_lines) {
# 下載並保存鏈接對應的文件
$filename = [System.IO.Path]::GetRandomFileName() + ".png"
Write-Host "隨機文件名: $filename"
Invoke-WebRequest -Uri $text_line -OutFile $filename

# 替換括號內的鏈接爲處理後的文件名
(Get-Content "..\$file") -replace [regex]::Escape($text_line), $filename | Set-Content "..\$file"
}

使用

假設腳本命名 img.sh > img.sh xxx.md

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章