I know how to merge two tables to print alternative lines in a new file, but I want to merge every two lines from file1.txt with one line from file2.txt. As an example:
file1.txt is
A a aa
B b bb
C c cc
D d dd
and file2.txt is
E e ee
F f ff
I want to have
A a aa
B b bb
E e ee
C c cc
D d dd
F f ff
Using GNU sed, you can read and insert one line from the second file after every other line ("two skip two") of the first:
Slightly more long-winded implementation of the same in awk:
You can use the
paste
command for this:paste
, by default, takes lines from each input file, then merges them into a single line separated by tabs. Using-d '\n'
, we tell it to use newlines as the separator instead.-
is standard input, which is redirected in fromfile1.txt
(< file1.txt
). Sopaste
takes one line from standard input, then another line from standard input (effectively two lines fromfile1.txt
, then a line fromfile2.txt
and prints them out separated by newlines.Original shellscript
I thought the following shellscript would do it. The trick is to open the two files on separate file descriptors (here #4 and #5).
Test
Make the shellscript executable and run it,
The original shellscript stops, when reading to the end of file in one of the input files (so that only matching 2+1 lines are written to the output).
Modified shellscript
The following shellscript will continue reading and writing until all the files have reached end of file (so that all available lines are written to the output). This should match what the OP wants.