Skip to content

Instantly share code, notes, and snippets.

@konfou konfou/csv2tex.sh
Created May 16, 2017

Embed
What would you like to do?
convert *.csv to a TeX table
#!/usr/bin/env bash
#
# Convert CSV file(s) to a TeX table.
# trap SIGINT
trap 'trap - INT; kill -s INT "$$"' INT
caption="Πειραματικά δεδομένα."
label_template="tab:"
out_template="tab-"
format_data() {
cat $1 | perl -pe 's/,/\t\& /g;' -pe 's/\n/ \\\\\n/;'
}
format_content() {
local ccs=$(yes 'c' | head -n ${col_num} | tr -d '\n')
local label="${label_template}$1"
cat <<EOF
\begin{table}[hbt]
\centering
\begin{tabular}{${ccs}}
\hline
EOF
format_data "$1.csv" | sed '1 s/$/ \\hline\\hline/'
cat <<EOF
\hline
\end{tabular}
\caption{\small ${caption}}
\label{${label}}
\end{table}
EOF
}
file() {
local base=$(basename "$1" '.csv')
local col_num=$(awk -F, '{print NF}' $1 | sort -nu | tail -n 1)
format_content "${base}" ${col_num} > "${out_template}${base}.tex"
}
usage() {
cat <<EOF
$(basename $0) <mode> <source>
Usage:
$(basename $0) --file/-f <target> convert <target> file
$(basename $0) --dir/-d <target> convert all files in <target>
$(basename $0) --all same thing as doing --dir .
EOF
}
main() {
case $1 in
--file|-f) file "$2" ;;
--dir|-d)
find "$2" -type f -name '*.csv' | while read f; do
file "$f"
done ;;
--all|-a) main --dir . ;;
*) usage ;;
esac
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.