14 Say Something

批量重命名博客源文件

在决定每天更新这个博客之后,为了以后方便管理,我在每篇博客的文件名前面都加上了当天的日期,而此前的文件是没有这个命名习惯的,大概有四十多篇的样子。

但我一直懒得统一修改,因为有几十个文件,挨个修改的话还是比较麻烦。前几天忽然想到,现在有了 AI,岂不是一句话就能改完的事情。

于是把存放博客文件的文件夹复制了一份出来,用 antigravity 打开那个文件夹,让 Gemini 帮我读取文件里的元数据,并将元数据里的日期信息加到文件名称前面,参考其他有日期的文件。

Gemini 写了个简单的脚本,执行完之后自己删除了脚本,并且没有动 index.md 这个文件。全程不超过三分钟。我又让Gemini给我把修改过的文件按时间顺序列了个表格出来,对比了一下数量,随机抽查了几篇看内容有没有被改,就验收通过了。

之后把 hugo 本地目录里那些没有日期前缀的文件删掉,替换成重命名之后的文章,总计 46 篇。然后 hugo server 了一下检查效果,没有任何问题。

 1# 以下代码由 Claude  生成
 2import os
 3import re
 4
 5directory = "/Users/username/filepath"
 6date_pattern = re.compile(r"^date:\\s*['\\"]?(\\d{4})-(\\d{2})-(\\d{2})", re.MULTILINE)
 7
 8files_to_rename = []
 9
10for filename in sorted(os.listdir(directory)):
11    if filename == "_index.md" or filename == ".DS_Store" or filename.startswith("rename_script"):
12        continue
13    if re.match(r"\\d{8}-", filename):
14        continue
15    
16    filepath = os.path.join(directory, filename)
17    if not os.path.isfile(filepath):
18        continue
19        
20    try:
21        with open(filepath, 'r', encoding='utf-8') as f:
22            content = f.read()
23        
24        match = date_pattern.search(content)
25        if match:
26            year, month, day = match.groups()
27            new_prefix = f"{year}{month}{day}"
28            new_filename = f"{new_prefix}-{filename}"
29            files_to_rename.append((filename, new_filename))
30        else:
31            print(f"Skipping {filename}: No date found")
32    except Exception as e:
33        print(f"Error reading {filename}: {e}")
34
35print(f"Found {len(files_to_rename)} files to rename.")
36for old, new in files_to_rename:
37    print(f"Renaming {old} -> {new}")
38    os.rename(os.path.join(directory, old), os.path.join(directory, new))
39    
40# 以上代码由 Claude 生成

就这段代码,看起来很简单,不过在有 AI coding agents之前让我自己去学会的话,应该也是很难的。

#Blog #折腾