Skip to main content

md图片链接替换

批量替换图片url

自己的笔记都是采用md存储,且图片均为本地的服务器,所以发布博客的时候,需要一个脚本批量处理一下自己的所有md文件

import os,re
from typing import *

img_patten = r'!\[.*?\]\((.*?)\)|<img.*?src=[\'\"](.*?)[\'\"].*?>'
img_match = re.compile(img_patten)

def replace_url(md_file_path:str, old:str, new:str) -> str:


md_data_new = ""
with open(md_file_path, 'r', encoding='utf-8') as f:
for each in f.readlines():
# print(each)
res = img_match.findall(each)
if res and len(res) > 0:
# print(res[0])
md_data_new += each.replace(old, new)

else:
md_data_new += each

with open(md_file_path, 'w', encoding='utf-8') as f:
f.write(md_data_new)

return md_data_new
if ( __name__ == "__main__"):
target_path = os.path.abspath(r'D:\CPS\MyProject\gitee\cps\NoteBooks\【01】前端相关\JavaScript\实用demo\【canvas】画框拖拽.md')
search_str = r'https://gitee.com/capsion/markdown-image/raw/master/image/'
replace_str = r'http://localhost:45462/image/'

replace_url(target_path, search_str, replace_str)

完整脚本

# -*- coding: utf-8 -*-
#
# @Author: CPS
# @email: 373704015@qq.com
# @Date: 2022-05-08 07:52:37.666466
# @Last Modified by: CPS
# @Last Modified time: 2022-05-08 07:52:37.666466
# @file_path "D:\CPS\MyProject\test"
# @Filename "replace.py"
# @Description: 功能描述
#

from typing import *

import os,re
from typing import *

img_patten = r'!\[.*?\]\((.*?)\)|<img.*?src=[\'\"](.*?)[\'\"].*?>'
img_match = re.compile(img_patten)

def replace_md_img(md_file_path:str, old:str|list[str], new:str) -> str:
md_data_new = ""
with open(md_file_path, 'r', encoding='utf-8') as f:
for each_line_str in f.readlines():
# print(each_line_str)
res = img_match.findall(each_line_str)
if res and len(res) > 0:
md_data_new += each_line_str.replace(old, new)
else:
md_data_new += each_line_str

with open(md_file_path, 'w', encoding='utf-8') as f:
f.write(md_data_new)

return md_data_new

def list_dir(path:str):
for dir_path, dir_list, file_list in os.walk(path):
print(f'当前文件夹: {dir_path}')

for file_name in file_list:
print(file_name)

def match_file(dir_path:str, exp:str='**/*.md'):
os.chdir(dir_path)

import glob
result_list = []
for name in glob.glob(exp, recursive=True):
file_path = os.path.join(dir_path, name)
if os.path.exists(file_path):
result_list.append(file_path)
return result_list


if ( __name__ == "__main__"):
target = r'W:/CPS/MyProject/cps/NoteBooks/【13】Game/'

matchs = 'https://gitee.com/capsion/markdown-image/raw/master/image/'
replace = 'http://localhost:45462/image/'

file_list = match_file(target)
for each in file_list:
replace_md_img(each, matchs, replace)