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

307 Views Asked by At

Starting with this,

example.txt

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

Going to this,

apendedtext.txt

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

There are 2 best solutions below

1
lucaslugao On BEST ANSWER

Assuming you added the line numbers for simplicity and that the output is missing the 8th line "erty" you can get around with a simple awk one-liner:

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

If you want to manipulate the line numbers too you could remove and add them back:

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

awk ' {print;} NR % 2 == 0 { print "append"; }' example.txt > appended.txt