Merge alternate lines from two files
Using paste
:
paste -d \\n file2 file1
Another awk solution:
awk '{print; getline < "file1"; print}' file2
The paste
solution is the most portable and most efficient. I'm only mentioning this alternative in case you prefer its behaviour in the case where the two files don't have the same number of lines:
With GNU sed
:
sed Rfile1 file2
If file1
has fewer lines than file2
, then when file1
is exhausted, sed
will not output anything for it (as opposed to empty lines for paste
).
If file1
has more lines than file2
, then those extra lines will be discarded (as opposed to printing empty lines for file2
with paste
).
$ paste a b
1 a
2 b
3
4
$ paste -d \\n a b
1
a
2
b
3
4
$ sed Rb a
1
a
2
b
3
4
$ sed Ra b
a
1
b
2