You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何每隔2行向文本文件中插入指定的新行内容

每隔2行插入指定内容的实现方案

方法1:Linux/macOS 终端awk实现(最快)

直接执行以下命令即可得到目标文件:
awk 'BEGIN{print "append"} {print} NR%2==0{print "append"}' example.txt > appendedtext.txt
如果需要完全匹配你给出的示例(舍弃原始文件最后一行erty),调整为:
awk 'BEGIN{print "append"} NR<=4{print} NR%2==0{print "append"}' example.txt > appendedtext.txt
逻辑说明:

  • BEGIN块在读取原始文件前先输出第一行插入内容
  • 逐行输出原始文件内容
  • 每读完2行原始内容,额外输出一行插入内容

方法2:Python跨平台实现(全系统通用)

运行以下Python代码即可完成处理:

# 自定义配置
input_file = "example.txt"
output_file = "appendedtext.txt"
insert_text = "append"
insert_interval = 2

with open(input_file, "r", encoding="utf-8") as f_in, open(output_file, "w", encoding="utf-8") as f_out:
    # 写入开头的插入内容
    f_out.write(f"{insert_text}\n")
    line_cnt = 0
    for line in f_in:
        f_out.write(line)
        line_cnt += 1
        if line_cnt % insert_interval == 0:
            f_out.write(f"{insert_text}\n")

如果需要匹配示例输出,在循环里加if line_cnt >=4: break即可。

方法3:Linux 终端sed实现

sed '1i\append' example.txt | sed '0~2a\append' | head -7 > appendedtext.txt

内容的提问来源于stack exchange,提问作者an0nhi11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:00:02