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:
sed Rfile2.txt file1.txt >file3.txt
paste -d '\n' file1.txt file2.txt >file3.txt
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
$ awk '{print} (FNR % 3)==0{getline<"file2.txt"; print}' file1.txt
1
2
3
A
4
5
6
B
How it works
print
This prints each line from file1.txt.
(FNR % 3)==0{ getline <"file2.txt"; print}
On every third line, this prints a line from file2.txt.
Some people strongly oppose use of awk's getline
. In that case:
$ awk 'FNR==NR{a[NR]=$0;next} {print} (FNR % 3)==0{print a[FNR/3]}' file2.txt file1.txt
1
2
3
A
4
5
6
B
How it works
FNR==NR{a[NR]=$0;next}
While reading the first file, file2.txt
, we save its lines in array a
and then skip the rest of the commands and jump to the next
input line.
print
If we have gotten here, then we are reading the second file, file1.txt
and we print its line.
(FNR % 3)==0 {print a[FNR/3]}
If the line number in file file1.txt
is an even multiple of 3, then we print the line from file file2.txt
whose line number is one third of the current line in file1.txt
.
Using python:
with open(sys.argv[1], 'rU') as f1, open(sys.argv[2], 'rU') as f2:
while f1 or f2:
for i, line in enumerate(f1):
print line.strip()
if i == 2:
break
if f2:
try:
print(next(f2).strip())
except StopIteration:
f2 = None
1
2
3
A
4
5
6
B