如题, 要求是把 旧格式的图片引用

1
![](imageurl)

批量替换为 新主题格式

1
{% image imageurl %}

Python实现

这种方式需要电脑中有Python环境, 虽然配置环境也比较简单, 但是还是需要一些门槛

注意修改脚本中的文件夹路径为自己的即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import os
import re

# 要处理的文件夹路径,例如 Hexo 的 source/_posts
ROOT_DIR = "./source/_posts"

# 匹配旧格式:![](URL)
pattern = re.compile(r'!\[\]\((https://[^)]*)\)')

def replace_in_file(file_path):
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()

# 替换为新格式:{% image URL %}
new_content = pattern.sub(r'{% image \1 %}', content)

if new_content != content:
with open(file_path, "w", encoding="utf-8") as f:
f.write(new_content)
print("Updated:", file_path)

def walk_dir(root):
for root_dir, _, files in os.walk(root):
for filename in files:
if filename.endswith(".md"):
full_path = os.path.join(root_dir, filename)
replace_in_file(full_path)

if __name__ == "__main__":
walk_dir(ROOT_DIR)
print("Done.")

VSCode一键替换

VSCode还是好用啊, 相比于写脚本来实现, VSCode的全局搜索支持正则表达式, 可以一键替换文件夹中所有内容

搜索:

1
!\[\]\((https:\/\/[^)]*)\)

替换:

1
{% image $1 %}