Skip to content

Instantly share code, notes, and snippets.

@stanleyxu2005
Last active February 2, 2024 12:12
Show Gist options
  • Save stanleyxu2005/5f344fb5f477fcb125acc364612d4d50 to your computer and use it in GitHub Desktop.
Save stanleyxu2005/5f344fb5f477fcb125acc364612d4d50 to your computer and use it in GitHub Desktop.
Pretty print csv to HTML table
#!/usr/bin/env bash
# Licensed under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Parameters
export DELIM="|"
export STATUS_COL="status"
export NUM_COLS_CSV="cpu,mem,uptime"
export CAPTION=
# Local variables
STATUS_COL_INDEX=-1
NUM_COLS_INDEX_CSV=
function parse_and_create_table() {
echo -n "<table>"
is_th=1
while read -r line
do
# Leading delimiter must be removed, otherwise the first column will be blank
line=$(sed -e "s/^$DELIM//; s/$DELIM$//;" <<< "$line")
if [[ $is_th -eq 1 ]]
then
determine_special_col_index_vars "$line"
fi
create_tr_row $is_th "$line"
is_th=0
done
if [[ -n $CAPTION ]]
then
echo -n "<caption>$CAPTION</caption>"
fi
echo "</table>"
}
function determine_special_col_index_vars() {
IFS=$DELIM read -ra cols <<< "${1}"
STATUS_COL_INDEX=$(find_elem_index "$STATUS_COL" "${cols[@]}")
IFS="," read -ra num_cols <<< "$NUM_COLS_CSV"
for col in "${num_cols[@]}"
do
index=$(find_elem_index "$col" "${cols[@]}")
if [[ $index -gt -1 ]]
then
NUM_COLS_INDEX_CSV+="$index,"
fi
done
# debug
#echo "STATUS_COL_INDEX=${STATUS_COL_INDEX}"
#echo "NUM_COLS_INDEX_CSV=${NUM_COLS_INDEX_CSV[*]}"
}
function create_tr_row() {
awk \
-v is_th="${1}" \
-v delim="$DELIM" \
-v status_col="$STATUS_COL_INDEX" \
-v num_col_csv=",$NUM_COLS_INDEX_CSV" \
'
function trim_and_html_safe(s) {
gsub(/^ +| +$/, "", s)
gsub(/</, "&lt;", s)
gsub(/>/, "&gt;", s)
return s
}
{
n = split($0, values, delim)
tag = is_th ? "th" : "td"
printf("<tr>")
for (i = 1; i <= n; i++) {
value = trim_and_html_safe(values[i])
col = i - 1
attr1 = !is_th && col == status_col ? sprintf(" status=\"%s\"", value) : ""
attr2 = match(num_col_csv, sprintf(",%d,", col)) ? " right" : ""
printf("<%s>%s</%s>", tag attr1 attr2, value, tag)
}
printf("</tr>")
}
' <<< "${2}"
}
function find_elem_index() {
text="${1}"
shift
cols=("${@}")
for (( i = 0; i < ${#}; i ++))
do
if [[ "$(trim "${cols[i]}")" = "$text" ]]
then
echo "$i"
return
fi
done
echo -1
}
function trim() {
echo "${1}" | xargs
}
# test command
parse_and_create_table < pm2.out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment