|总字数624|阅读时长2分钟

2023/02/06 更新

VSCode 集成了 某路径下的文件批量替换指定内容 的功能,更方便

image-20230206183933193

1. 前言

jsd 失效之后,博主使用了新的图床方案,需将文章的原 jsd 图片链接替换为新的图片地址

这类脚本在网上有很多,都很推荐,如

2. 脚本内容

源码来自:批量修改文件内容(Python版)

脚本采用递归的方式,遍历 43~46 行 目录下的所有文件,进行批量替换

说明:

  1. 根据自身情况修改 43~46 行 需遍历的目录;修改 47、48 行 需要替换的内容

  2. 脚本第 24 行 限制了只筛选出 Markdown 类型的文本文件进行修改,如需修改其他类型的文本文件 需自行更改后缀进行匹配

  3. 执行前请先备份源文件,以防出错后无法还原

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66





import os
import re





def search(search_path, search_result):

all_file = os.listdir(search_path)

for each_file in all_file:

if os.path.isdir(search_path + each_file):

search(search_path + each_file + '/', search_result)

else:
if re.findall('.*\.md$', each_file) == [each_file]:

search_result.append(search_path + each_file)




def replace(replace_file_name, replace_old_str, replace_new_str):
with open(replace_file_name, "r", encoding = "UTF-8") as f1:
content = f1.read()
f1.close()
t = content.replace(replace_old_str, replace_new_str)
with open(replace_file_name, "w", encoding = "UTF-8") as f2:
f2.write(t)
f2.close()




path_list = [
'E:/code_zone/hexo-source/source/_posts/',
'E:/code_zone/hexo-source-butterfly/source/_posts/',
]
old_str = 'https://cdn.iocdn.cc/npm/mycpen-image-bed@0.0.0-flvvbcbcgo/image/'
new_str = 'https://cdn.iocdn.cc/npm/mycpen-image-bed@0.0.0-flvvbcbcgo/image/'

search_result = []

if __name__ == '__main__':
result = []


for path in path_list:
search(path, result)
count = 0
for file_name in result:
replace(file_name, old_str, new_str)
count += 1
print("{} done {}".format(file_name, count))




3. 参考文章

源码来自:批量修改文件内容(Python版)

版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明来自 Mycpen

赞助作者


欢迎访问 MYCPEN BLOG

建站初衷 记录学习历程,整理平时发现并解决的问题

最近发布

13_Hexo-操作记录

12_Hexo-GitHub Actions 发布博客静态资源至 NPM

06_转载-自我提升的8个好习惯

05_转载-延寿指南-反向面试-文档写作规范

04_转载-提问的智慧