Issues with AWK scripting for HTML tags

2019-09-21 09:29发布

问题:

Below is the data file(results) contents-

13450708,13470474,US,15

24954,24845,JPN,44

14258992,14365059,US,4

24954,24845,IND,44

I want to send above data sets to email in a tabular format. For that I am using below awk script. Now the challenge I am facing here is - I want to make the background color as red if the lastfield in the datasets ( i.e. here 15,44,4,44) > 40. Can you please tell me how to use the same in below code.

awk 'BEGIN{

FS=","

print  "<HTML>""<TABLE border="1"><TH>Store_count</TH><TH>Store_sold</TH><TH>Store_code</TH><TH>Backlogs</TH>"

}

 {

printf "<TR>"

for(i=1;i<=NF;i++)

printf "<TD>%s</TD>", $i

print "</TR>"

 }

END{

print "</TABLE></BODY></HTML>"

 }

' results > file1.html

回答1:

I really don't understand why you're struggling with this since you seem to already have all of the information to do what you want, but anyway - just change:

printf "<TD>%s</TD>", $i

to

printf "<TD%s>%s</TD>", ( (i==NF) && ($i > 40) ? " style=\"background-color:red\"" : "" ), $i

or if you don't like ternary expressions:

printf "<TD"
if ( (i==NF) && ($i > 40) ) {
    printf " style=\"background-color:red\""
}
printf ">%s</TD>, $i

or similar.



回答2:

Anyways realized where I did the mistake anyways for me below code is giving results as expected. for(i=1;i<=NF;i++)

if (i ==4 && $4 >= 40)

{

printf "%s", $i

}

else

{

printf "%s", $i

}

print ""

}

END{

print ""

}

' results1 > file1.html



标签: shell awk