arnpry
arnpry

Reputation: 1141

Add Double Quotes Around Output Field

I'm trying to surround awk output fields with double quotes but, keep running into errors. This code is running in a bash script on an Ubuntu system

Errors

awk: cmd. line:1: BEGIN {print "<table id="\"alert\"",">"} ; {  print "<tr><td class="\"site\"",">" $1 "</td><td class="\"fdate\"",">" $2 "</td><td class="\"prcp\"",">" $3 "</td><td class="\"snow\"",">" $4 "</td><td class="\"tmp2m\"",">" $5 "</td><td class="\"dpt2m\"",">" $6 "</td><td class="\"wchill\"",">" $7 "</td><td class="\"wind10m\"",">" $8 "</td></tr>"} ; END { print "</table>"}
awk: cmd. line:1:                          ^ backslash not last character on line
awk: cmd. line:1: BEGIN {print "<table id="\"alert\"",">"} ; {  print "<tr><td class="\"site\"",">" $1 "</td><td class="\"fdate\"",">" $2 "</td><td class="\"prcp\"",">" $3 "</td><td class="\"snow\"",">" $4 "</td><td class="\"tmp2m\"",">" $5 "</td><td class="\"dpt2m\"",">" $6 "</td><td class="\"wchill\"",">" $7 "</td><td class="\"wind10m\"",">" $8 "</td></tr>"} ; END { print "</table>"}
awk: cmd. line:1:                          ^ syntax error

Attempted Code

awk -F, 'BEGIN {print "<table id="\"alert\"",">"} ; {  print "<tr><td class="\"site\"",">" $1 "</td><td class="\"fdate\"",">" $2 "</td><td class="\"prcp\"",">" $3 "</td><td class="\"snow\"",">" $4 "</td><td class="\"tmp2m\"",">" $5 "</td><td class="\"dpt2m\"",">" $6 "</td><td class="\"wchill\"",">" $7 "</td><td class="\"wind10m\"",">" $8 "</td></tr>"} ; END { print "</table>"}' /home/weather/csv > /home/weather/csv.html

Upvotes: 0

Views: 87

Answers (2)

Ed Morton
Ed Morton

Reputation: 204638

Here's how you should really be approaching this (untested):

awk -F, '
BEGIN {
    split("site,fdate,prcp,snow,tmp2m,dpt2m,wchill,wind10m",tags)
    print "<table id=\"alert\">"
}
{
    printf "<tr>"
    for (i=1; i in tags; i++) {
        printf "<td class=\"%s\">%s</td>", tags[i], $i
    }
    print "</tr>"
}
END { print "</table>"}
' /home/weather/csv

Upvotes: 1

jas
jas

Reputation: 10865

You've got too many quotes going on, and you probably don't want to separate the individual items to be printed with commas:

$ awk -F, 'BEGIN {print "<table id=\"alert\"" ">"}'
<table id="alert">

Sometimes it helps to set the double quote as a variable to make things more readable:

$ awk -F, -v q='"' 'BEGIN {print "<table id=" q "alert" q ">"}'
<table id="alert">

Upvotes: 2

Related Questions