Skip to content

Instantly share code, notes, and snippets.

@jschaub30
Last active July 1, 2023 18:46
Show Gist options
  • Select an option

  • Save jschaub30/c67cf9e214d83accd4db to your computer and use it in GitHub Desktop.

Select an option

Save jschaub30/c67cf9e214d83accd4db to your computer and use it in GitHub Desktop.
Bash script to convert a simple CSV file into an HTML table
#!/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>"
@jikuja
Copy link
Copy Markdown

jikuja commented Aug 10, 2018

Does not work with complex CSV files. Will fail if field data contains comma or newlines.

@jatinbamel9696
Copy link
Copy Markdown

how can we add border

@go2amp
Copy link
Copy Markdown

go2amp commented Jun 27, 2023

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

?

@jschaub30
Copy link
Copy Markdown
Author

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