4

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
0

3 Answers 3

9

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
4
$ 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.

Alternative

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.

0

Using python:

Code:

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

Results:

1
2
3
A
4
5
6
B

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .