如何在已有文档开头插入以修改后文件名命名的标题?
批量给文档开头插入文件名作为标题的解决方案
以下是不同平台下的可行方法,按需选择:
Linux/macOS:使用 sed 命令
利用 sed 的行插入功能,直接在文件第一行添加标题。
针对 macOS(BSD sed)
for file in *.md; do # 提取不含后缀的文件名作为标题 title="# ${file%.*}" # 在文件开头插入标题 sed -i '' "1i\\ $title " "$file" done
针对 Linux(GNU sed)
语法更简洁:
for file in *.md; do title="# ${file%.*}" sed -i "1i $title" "$file" done
Windows:使用 PowerShell
通过读取文件内容并前置标题的方式实现:
Get-ChildItem -Path .\ -Filter *.md | ForEach-Object { $title = "# $($_.BaseName)" $content = Get-Content $_.FullName $title, $content | Set-Content $_.FullName }
跨平台:Python 脚本
适合需要自定义处理逻辑(比如先修改文件名再生成标题)或处理特殊编码文件的场景:
import os # 可修改后缀名匹配需要处理的文件 target_ext = '.md' for filename in os.listdir('.'): if filename.endswith(target_ext): # 提取文件名(不含后缀)生成标题 base_name = os.path.splitext(filename)[0] title = f"# {base_name}\n\n" # 读取并写入内容 with open(filename, 'r', encoding='utf-8') as f_in: content = f_in.read() with open(filename, 'w', encoding='utf-8') as f_out: f_out.write(title + content)
注意事项
- 替换示例中的
.md为你实际处理的文件后缀 - 建议先备份文件再执行批量操作,避免意外丢失内容
内容的提问来源于stack exchange,提问作者PeterP
相关产品推荐
相关产品推荐

