如何在文本文件中每隔两行插入一个新行?

How can I insert a new line into a text file into every other 2 lines?

从这里开始,

example.txt

1.qwer
2.asdf
3.xzcv
4.cbvn
5.erty

转到这个,

apendedtext.txt

1.append
2.qwer
3.asdf
4.append
5.xzcv
6.cbvn
7.append

awk ' {print;} NR % 2 == 0 { 打印“追加”; }' example.txt > appended.txt

假设您为简单起见添加了行号,并且输出缺少第 8 行“erty”,您可以使用一个简单的 awk 单行代码:

#                                     ┌─ input      ┌─ output
awk 'NR % 2 {print "append"} {print}' < example.txt > apendedtext.txt
#     │                      └─ Print the original line
#     └─ Append if line has even index          

如果你也想操纵行号,你可以删除并重新添加它们:

( sed -E 's/[0-9]*\.//g'| awk 'NR % 2 {print (++i) "." "append"} {print (++i) "." [=11=]}' ) < example.txt > apendedtext.txt
#           └─ Remove line number               └─   Prepend a counter  ─┘