Last active
July 1, 2023 18:46
-
-
Save jschaub30/c67cf9e214d83accd4db to your computer and use it in GitHub Desktop.
Bash script to convert a simple CSV file into an HTML table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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>" |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how can we add border