FOR loop with multiple files as input and awk

Hi all ,

i want to pass multiple files as input to a for loop


for i in file1 file2 file3
do
some awk action < $i >> $i.out
done

but im getting error in that for loop is the way i use to pass files to awk using for correct and
2.we can directly pass multiple files to awk as input but how to out put results to different output files

Create output file names using FILENAME which is the name of the file awk is currently reading.

awk ' { F = FILENAME ".out"; print $0 > F } ' file1 file2 file3
1 Like

HI Bipanajith ,

Thanks buddy

Thanks for ur reply we need to use it in the END { } or any where will do .

Show your awk program, or we'll never guess right.

Hi,

this is my awk part (original which i used did not modify as suggested till now)

for i in file_1 file_2 file_3

do

awk -F, ' BEGIN {
              print "<table border=1>"
} NR == 1 {
print "<tr>"
for(i=1;i<=NF;i++){
print "<th><b><font face=\"verdana\"><font size=\"2\"><font color=\"Brown\">" $i"</font></b></th>"
}
print "</tr>"
} NR > 1 {
print "<tr>"
for(i=1;i<=NF;i++) {
print "<td><b><font face=\"verdana\"><font size=\"2\"><font color=\"Black\">" $i"</font></b></td>"
}
print "</tr>"
} END {
                print "</table>"
} ' $i >> $i.html

done

so i can use the mutiple file names in the at the end portion as output files as suggested by bipanajith i.e using filename variable of awk is it or is there any better way

Sure. Whenever you do print, do print ... > FILENAME ".html"

And instead of NR use FNR

1 Like

Hi corona,

when i use FNR instead of NR in the above code and redirecting the print as suggested im getting output is last file.html iwth only </table> in it can u tell me where im i wrong

That will not work at all. The END section is executed at the end of the ENTIRE input stream, i.e. after all files have been processed.
You can make awk work on multiple files, and even print out to respective output files, but you will have to check for a "file change" in the input stream by either comparing the FILENAME variable or by testing FNR == 1 - in the program body! There's many an example in them there threads...