@Fravadona's answer is good, here's just an alternative approach, using any POSIX awk, to consider that's IMO not anysignificantly better aside from a couple of cosmetic differences, it/bells and whistles. It mainly just isolates each specific part of the output a bit further by providing a separate function for each level/segment of HTML (html/body/table/rows/row/cells/cell) which might make it a bit easier and less error prone to modify that one part of itif necessary in future:
$ cat tst.sh
#!/usr/bin/env bash
awk '
BEGIN {
FS = "[|]"
Indent = -2
prt_html()
exit
}
function prt_html() {
prt_beg("<html>")
prt_body()
prt_end("</html>")
}
function prt_body() {
prt_beg("<body>")
prt_table()
prt_end("</body>")
}
function prt_table() {
prt_beg("<table border=1 cellspacing=0 cellpadding=3>")
numHdrCells = prt_rowprt_hdr_row(0,"SID|PID|Username|Database|Hostname|Program|Connected|Idle Time|Query Time|EST COST|SEQ SCAN|Query")
prt_rowsprt_data_rows(numHdrCells)
prt_end("</table>")
}
function prt_rowsprt_data_rows(numHdrCells, line) {
while ( (getline line) > 0 ) {
prt_rowprt_data_row(numHdrCells,line)
}
}
function prt_rowprt_hdr_row(numHdrCells,s, numCells) {
prt_beg("<tr>")
numCells = prt_cellsprt_hdr_cells(numHdrCells,s)
prt_end("</tr>")
return numCells
}
function prt_cellsprt_data_row(numHdrCells,s,) {
cellType,numCells,f,i) {
prt_beg("<tr>")
numCells = splitprt_data_cells(snumHdrCells,s)
f, /[|] prt_end("</tr>")
}
iffunction prt_hdr_cells(s, numHdrCells == 0 numCells,f,i) {
numCells = split(s, f)
# We are printing the header row
for (i = 1; i <= numCells; i++) {
cellType = "th"
}prt_cell("th",f[i])
else {}
return numCells
# We}
are printing a datafunction row
prt_data_cells(numHdrCells,s, f,i) {
cellType =split(s, "td"f)
# Force the number of cells printed for each data row
# to match the number of cells printed for the header.
numCells = numHdrCells
}
for (i = 1; i <= numCells;numHdrCells; i++) {
prt_cell(cellType"td",f[i])
}
return numCells
}
function prt_cell(cellType,s) {
Indent += 2
# Strip any leading/trailing white space around this cell
gsub(/^[[:space:]]+|[[:space:]]+$/, "", s)
prt_indented("<" cellType ">" escape_html(s) "</" cellType ">")
Indent -= 2
}
function escape_html(s) {
gsub(/&/, "\\&", s)
gsub(/</, "\\<", s)
gsub(/>/, "\\>", s)
return s
}
function prt_beg(s) { Indent += 2; prt_indented(s) }
function prt_end(s) { prt_indented(s); Indent -= 2 }
function prt_indented(s) { printf("%*s%s\n", Indent, "", s) }
' "${@:--}"