Last active
July 1, 2017 14:12
-
-
Save Decstasy/1e81bc0cccb4d653c6b7a54243f3e63e to your computer and use it in GitHub Desktop.
Convert csv to ascii table (mysql style)
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/ksh | |
# Dennis Ullrich | |
# Version 1.0-0 (2017-07-01) | |
# [email protected] | |
csv2ascii(){ | |
if [[ $# -ne 2 ]]; then | |
echo "$0 [separator] [file or \"-\" for stdin]" | |
return false | |
fi | |
# Variables | |
separator="$1" | |
input="`cat $2`" || return $? | |
# Internal vars | |
max=( 0 ) | |
format="|" | |
spacer="+" | |
# Get max character count per field | |
while read line; do | |
IFS="$separator" array=( $line ) | |
for i in ${!array[*]}; do | |
[[ ${#array[i]} -gt ${max[i]} ]] && max[i]=${#array[i]} | |
done | |
done <<< "${input}" | |
# Build printf format string and spacer | |
for i in ${max[*]}; do | |
format+=" %-${i}b |" | |
spacer+="-$(printf '\-%.0s' {1..$i})-+" | |
# If bash is used: | |
#spacer+="-$(printf "%${i}s" "-")-+" | |
done | |
# If bash is used: | |
#spacer="${spacer// /-}" | |
# Ascii table output | |
i=0 | |
echo "$spacer" | |
while read line; do | |
IFS="$separator" printf "${format}\n" ${line} | |
# Spacer to separate headline from body | |
# This causes trouble if bash is used - rewrite it as if []; then ... fi | |
[[ $i -eq 0 ]] && { echo "$spacer"; ((i++)) } | |
done <<< "${input}" | |
echo "$spacer" | |
} | |
csv2ascii $@ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment