我在csv文件中有如下所示的数据
ServerName,Index,Status
10.xxx.xx.xx,1.5.1.1,2
10.xxx.xx.xx,1.5.1.2,3如果"Status“的值为3/4/5,我需要将这些数据转换为html,并将行涂上颜色。请帮我这个忙。试在下面
awk 'BEGIN{
FS=","
print "<HTML>""<TABLE border="1"><TH>JOB_NAME</TH><TH>RUN_DATE</TH><TH>STATUS</TH>"
}
{
printf "<TR>"
for(i=1;i<=NF;i++)
printf "<TD>%s</TD>", $i
print "</TR>"
}
END{
print "</TABLE></BODY></HTML>"
}
' 10.106.40.45_FinalData.csv > file.html
sed -i "s/2/<font color="green">2<\/font>/g;s/4/<font color="red">4<\/font>/g;s/5/<font color="red">5<\/font>/g;" file.html在我尝试过的最新代码中,我只需要检查status列的值,并且需要对单元格着色。
发布于 2019-03-12 14:07:15
$ cat tst.awk
BEGIN{
FS = ","
colors[3] = "red"
colors[4] = "green"
colors[5] = "blue"
print "<HTML><BODY>"
print "<TABLE border=\"1\">"
print "<TR><TH>JOB_NAME</TH><TH>RUN_DATE</TH><TH>STATUS</TH></TR>"
}
NR>1 {
printf "<TR>"
for (i=1; i<=NF; i++) {
if ( (i == NF) && ($i in colors) ) {
on = "<font color=\"" colors[$i] "\">"
off = "</font>"
}
else {
on = off = ""
}
printf "<TD>%s%s%s</TD>", on, $i, off
}
print "</TR>"
}
END {
print "</TABLE>"
print "</BODY></HTML>"
}。
$ awk -f tst.awk file
<HTML><BODY>
<TABLE border="1">
<TR><TH>JOB_NAME</TH><TH>RUN_DATE</TH><TH>STATUS</TH></TR>
<TR><TD>10.xxx.xx.xx</TD><TD>1.5.1.1</TD><TD>2</TD></TR>
<TR><TD>10.xxx.xx.xx</TD><TD>1.5.1.2</TD><TD><font color="red">3</font></TD></TR>
</TABLE>
</BODY></HTML>发布于 2019-03-12 12:31:54
你并没有说问题出在哪里,但我猜想,当这些数字出现在地址中时,它也会使数字着色?
最好的解决方案可能是在awk脚本中添加一个条件(未经测试):
if (i == 3 && $i == 2) {
print "<TD><font color="green">2<\/font></TD>"
} else .....另一种情况是,状态字段是列中的唯一数字,而地址不是,因此可以调整模式匹配:
"s/>2</><font color="green">2<\/font></g;......"即匹配周围的括号。
发布于 2021-06-30 15:55:55
您也可以将jq用于此任务。jq构造CSV数据,而不是只在文本基础上工作。这使得移除空行或只对“Status”列着色很容易。
#!/bin/bash
CSV='
ServerName,Index,Status
10.xxx.xx.xx,1.5.1.1,2
10.xxx.xx.xx,1.5.1.2,3
'
jq -srR '
def colorize($status):
if $status == "3" then "yellow"
elif $status == "4" then "orange"
elif $status == "3" then "red"
else "green"
end
| "<font color=\"\(.)\">\($status)</font>";
split("\n") # split lines
| map(select(length > 0)) # remove empty lines from CSV
| map(split(",")) # split each line
| .[1:] # drop first line with headers
| "<table>", # convert to HTML table
" <tr> <th>ServerName</th> <th>Index</th> <th>Status</th> </tr>",
(.[] | " <tr> <td>\(.[0])</td> <td>\(.[1])</td> <td>\(colorize(.[2]))</td> </tr>"),
"</table>"
' <<< "$CSV"产出:
<table>
<tr> <th>ServerName</th> <th>Index</th> <th>Status</th> </tr>
<tr> <td>10.xxx.xx.xx</td> <td>1.5.1.1</td> <td><font color="green">2</font></td> </tr>
<tr> <td>10.xxx.xx.xx</td> <td>1.5.1.2</td> <td><font color="yellow">3</font></td> </tr>
</table>https://stackoverflow.com/questions/55120416
复制相似问题