For loop inside awk to read and print contents of files

Hello,
I have a set of files Xfile0001 - Xfile0021, and the content of this files (one at a time) needs to be printed between some line (lines start with word "Generated") that I am extracting from another file called file7.txt and all the output goes into output.txt. First I tried creating a for loop over the Xfiles, and inside the loop the awk code, but didn't work, I understand I have to use the for loop inside the awk command, but after trying many times, I am not getting the output I am looking for.
So far this is one of the several versions I have:

awk '/Generated/ {print;getline; for (i in Xfile????); print "$i"; next}' file7.txt > output.txt

So far this gives me an error, now I realized the question mark is not properly understood as 'interchangeable' character within awk, and also the print "$i" prints literally $i and not the content of the corresponding Xfile. I have recently started using more unix commands to try to do more efficiently my work, and its been very useful (whenever I get through this kind of things). I will really appreciate if someone can help me here.
By the way, the output I expect to have on output.txt should look like this:

<first line saying "Generated ....." from file7.txt>
<content of Xfile0001>
<second line saying "Generated ..." from file7.txt>
<content of Xfile0002>
...
...
...

Thank you very much,

$ does not mean "variable" in awk -- it means column. If you did V=5; print $V you'd be printing the 5th column. Leave off the $, and you'd just be printing the value 5.

awk cannot do globbing like in shell, but it can read from arbitrary files. Perhaps this?

awk '/Generated/ {print;getline;  file++;
        while((getline <sprintf("Xfile%04d",file))>=0) print;
        close(sprintf("Xfile%04d", file)); }' inputfile

Thanks for your reply, and for the hint on the use of $. I used the code you suggested, but what is doing is to get the first line that says "Generated ..." from inputfile, then pastes the content of Xfile0001, and then it prints the last line of Xfile0001 'ad infinitum' until I disk quota is exceeded, and doesn't print the next line from inputfile saying "Generated..." followed by Xfile0002, and so on. Thanks!
I tried adding a next statement, but doestn't work. Thanks for your advice.

Change below statement to be > 0 as opposed to >= 0...

while ((getline < sprintf("Xfile%04d", file)) > 0) print;

Because when end-of-file is reached the >= 0 test will always be true creating an ad nauseum loop until "output.txt" fills up your disk partition.

2 Likes

Thank you so much, that does the trick :slight_smile: :slight_smile:

Sorry about that, awk's getline always confuses me. It uses neither the C nor C++ convention for return value on these things, but some weird hybrid of both, causing the usual while(getline) most programmers expect to become an infinite loop as well.