Search code examples
shellunix-text-processing

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


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

Solution

  • 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  ─┘