-
-
Save jschaub30/c67cf9e214d83accd4db to your computer and use it in GitHub Desktop.
#!/bin/bash | |
# Script to convert a *simple* CSV file into an HTML table | |
# Will fail if field data contains comma or newlines | |
# | |
# USAGE: bash csv2html.sh CSV_FN [BORDER_WIDTH] > OUTPUT_HTML_FN | |
usage (){ | |
echo "USAGE: $0 CSV_FN [BORDER_WIDTH] > OUTPUT_HTML_FN" | |
echo "Examples:" | |
echo "$0 /tmp/input.csv > /tmp/output.html" | |
echo "$0 /tmp/input.csv 1 > /tmp/output.html # add a border" | |
} | |
[[ $# -lt 1 ]] && usage && exit 1 | |
[[ $1 == "-h" ]] || [[ $1 == "--help" ]] && usage && exit 1 | |
CSV_FN=$1 | |
if [[ $# -eq 2 ]]; then | |
echo "<table border=\"$2\">" | |
else | |
echo '<table>' | |
fi | |
head -n 1 "$CSV_FN" | \ | |
sed -e 's/^/<tr><th>/' -e 's/,/<\/th><th>/g' -e 's/$/<\/th><\/tr>/' | |
tail -n +2 "$CSV_FN" | \ | |
sed -e 's/^/<tr><td>/' -e 's/,/<\/td><td>/g' -e 's/$/<\/td><\/tr>/' | |
echo "</table>" |
Does not work with complex CSV files. Will fail if field data contains comma or newlines.
how can we add border
I'm not following the usage. Can you give an example?
Supposed I have a csv at /tmp/fw30.csv and I want output to the finished product to /tmp/fw30.html
?
Apologies to all for not responding sooner and thanks for the comments and questions. I've just updated the script based on all of your feedback.
@alanwilcox862 I tested it on my system (Mac + Brave browser) and the column widths are indeed automatically adjusted.
@jikuja correct. I've added this to the comments at the top of the script.
@jatinbamel9696. I added the ability to create a simple border with the 2nd argument to the script.
@go2amp ,
./csv2html.sh /tmp/fw30.csv > /tmp/fw30.html
or
bash csv2html.sh /tmp/fw30.csv > /tmp/fw30.html
should do it. I also added this to the example usage.
Hi The above script works as advertised on large, complex csv files. Even in KSH on unix.... What I need next is a way to set or modify column widths. I thought by default, column widths in html tables were automatically adjusted ( to each field in between the '',"s in a csv file). Do I need to add a 'width auto' or 'width 100' right after the echo "
", above the "head -1" in the script above ? Once I get the syntax of this add I can test either 'auto' or '100' for width . Alan Wilcox [email protected]