How to interleave two txt files with alternative number of lines

awkcatsedtext processing

file1.txt:

1
2
3
4
5
6

file2.txt:

A
B
C
D
E

Desired output in 3 : 1 ratio (file3.txt)

1
2
3
A
4
5
6
B

Commands I have tried:

  1. sed Rfile2.txt file1.txt >file3.txt
  2. paste -d '\n' file1.txt file2.txt >file3.txt

Best Answer

With paste:

paste -d '\n' <file1.txt - - - file2.txt

though it would keep outputting lines after one of the files is exhausted if there are still lines left in the other file as in your sample.

With awk:

awk '{print}; NR % 3 == 0 {getline < "file2.txt"; print}' file1.txt

Or the GNU sed equivalent:

sed '3~3 R file2.txt' file1.txt

This time, stop as soon as file1.txt is exhausted but still carry on if file2.txt is exhausted (and output empty lines in the awk variant and nothing in the GNU sed variant).

To stop as soon as either file is exhausted:

awk '{print}
     NR % 3 == 0 {
       if ((getline < "file2.txt") <= 0) exit
       print
     }' file1.txt
Related Question