如何为章节下以数字+点开头的行添加对应章节号前缀
实现方案
方案1:使用awk命令(Linux/macOS终端直接运行)
适合类Unix系统用户,一行命令即可完成处理:
awk '/^chapter [0-9]+\./ {split($2, arr, "."); ch=arr[1]; print $0; next} /^[0-9]+\./ {print ch "." $0; next} 1' input.txt > output.txt
逻辑说明:
- 匹配到
chapter 数字.开头的行时,提取章节号存储到变量ch,直接输出原行 - 匹配到
数字.开头的行时,把存储的章节号拼接到原编号前面输出 - 其他非规则开头的行直接原样输出
方案2:使用Python脚本(全平台通用)
Windows、Linux、macOS都可以运行,兼容性更高:
current_chapter = "" # 替换input.txt为你的源文件路径 with open("input.txt", "r", encoding="utf-8") as f_in, open("output.txt", "w", encoding="utf-8") as f_out: for line in f_in: if line.startswith("chapter "): # 提取当前章节号 current_chapter = line.strip().split()[1].rstrip(".") f_out.write(line) elif line.split(".")[0].isdigit() and line[len(line.split(".")[0])] == ".": # 给数字开头的行加上章节前缀 f_out.write(f"{current_chapter}.{line}") else: # 普通行原样输出 f_out.write(line)
运行脚本后处理后的结果会保存在同目录的output.txt中,不会修改原文件,你可以先拿部分内容测试验证规则匹配正确后,再处理完整文件。
内容的提问来源于stack exchange,提问作者Jaime4447
相关产品推荐
相关产品推荐

