Reading and appending a row from file1 to file2 using awk or sed

Hi, I wanted to add each row of file2.txt to entire length of file1.txt given the sample data below and save it as new file. Any idea how to efficiently do it. Thank you for any help.

input file
file1.txt   file2.txt
140 30    200006 141 32     
140 32    200006 142 33
140 35    200006 142 30
140 36
140 50

desired outputs:
outfile1.txt
140 30 200006 141 32
140 32 200006 141 32
140 35 200006 141 32
140 36 200006 141 32
140 50 200006 141 32

outfile2.txt
140 30 200006 142 33
140 32 200006 142 33
140 35 200006 142 33
140 36 200006 142 33
140 50 200006 142 33

outfile3.txt
140 30 200006 142 30
140 32 200006 142 30
140 35 200006 142 30
140 36 200006 142 30
140 50 200006 142 30

awk 'NR == FNR {a[FNR] = $0; n = FNR; next}
{c++;
for(i = 1; i <= n; i++)
  {print a, $0 > "output" c ".txt"}}' file1.txt file2.txt
1 Like

Thank you for the quick reply and saving my day. :slight_smile:

This will work fine on many systems as long as there aren't too many lines in file2.txt. On other systems, you'll get a syntax error on the print statement. If there are a lot of lines in file2.txt, it may run out of file descriptors. The following minor changes avoid these possible problems:

awk '
NR == FNR {a[FNR] = $0; n = FNR; next}
{       c++;
        for(i = 1; i <= n; i++)
                print a, $0 > ("output" c ".txt")
        close("output" c ".txt")
}' file1.txt file2.txt
1 Like

Thank you for pointing that out. In the output file, how can I modify "c" to have the same length by adding leading zeros, such that output1.txt should be output01.txt?thanks again

awk '
NR == FNR {a[FNR] = $0; n = FNR; next}
{       f = sprintf("output%02d.txt", ++c)
        for(i = 1; i <= n; i++)
                print a, $0 > f
        close(f)
}' file1.txt file2.txt
1 Like