Created
May 16, 2017 11:59
-
-
Save konfou/c8d097a3bf1ba8a1ab5b1887c203572c to your computer and use it in GitHub Desktop.
convert *.csv to a TeX 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
#!/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