Reading a file several times with awk

Hi everyone,

I was wondering if it's possible to read a file ("file2" in my example) more than once. In this example I want to print file2 entirely for each lines of file1:

awk -F$'\t' '{
    print $0
    while ((getline < "file2") > 0) {
        print "\t"$0
    }
}' file1

It obviously doesn't work as is (only prints file2 for the first line), but I was hoping for a way to somehow "reinitialize" the getline cursor?

That could be very helpful for me!
Thanks :slight_smile:
Anthony

After the while loop, close the filehandle:

close "file2"

Regards,
Alister

awk -F'\t' '{
    print
    while ((getline < "file2") > 0) {
        print "\t" $0
    }
    close ("file2")    
}' file1

---------- Post updated at 10:13 PM ---------- Previous update was at 10:10 PM ----------

Or:

awk -F'\t' 'NR == FNR {
  f2 = f2 ? f2 RS OFS $0 : OFS $0
  next 
  }
{ print $0 RS f2 }
' OFS='\t' file2 file1  

---------- Post updated at 10:18 PM ---------- Previous update was at 10:13 PM ----------

I didn't know that there was an awk implementation that accepts that syntax (close with no parenthesis) and just found that AT&T awk doesn't complain (gawk does).

Brilliant, thanks a lot to both of you!

I wasn't either (or maybe I was, subconsciously ;)). I meant to use the usual function calling syntax with the parenthesis.

Nice catch, radoulov.

Regards,
Alister