Skip to content

Instantly share code, notes, and snippets.

@xmonader
Forked from m-motawea/table.sh
Created December 22, 2021 18:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xmonader/f086d9a5c872c7db44dd6873d5ab5478 to your computer and use it in GitHub Desktop.
Save xmonader/f086d9a5c872c7db44dd6873d5ab5478 to your computer and use it in GitHub Desktop.
make table in bash
#!/bin/bash
# the script to make tables like this
# +----------+--------+--------------------+
# |col1 |col2 |col3 |
# +----------+--------+--------------------+
# |val1 |val3 |val4 |
# +----------+--------+--------------------+
# |valqeefnkl|val3wekj|val4 |
# |1 |bkjwvsaj| |
# |bvjwsvbjbw| | |
# |vjkbjwdvbj| | |
# |wevbwjvbvw| | |
# |kjvjkvsbj | | |
# +----------+--------+--------------------+
column_len=( 10 8 20 )
table_vertical_separator="|"
table_horizontal_separator="-"
table_border_mark="+"
write_separate_line() {
for n in "${column_len[@]}"
do
echo -n $table_border_mark
for i in $(seq 1 $n); do echo -n $table_horizontal_separator; done
done
echo -n $table_border_mark
echo ""
}
write_row() {
printed=""
recurse=""
remaining_cols=()
ci=0
echo -n $table_vertical_separator
while (( "$#" )); do
value=$1
remaining=${column_len[ci]}
size=${#value}
substr=""
if [ "$size" -gt "$remaining" ]; then
let "start=remaining+1"
substr=`echo "$value" | cut -c$start-$size`
value=`echo "$value" | cut -c1-$remaining`
recurse="yes"
fi
remaining_cols+=($substr)
echo -n $value
let "remaining-=size"
for i in $(seq 1 $remaining); do echo -n " "; done
echo -n $table_vertical_separator
let "ci+=1"
shift
done
while [ $ci -lt "${#column_len[@]}" ]
do
remaining=${column_len[ci]}
for i in $(seq 1 $remaining); do echo -n " "; done
echo -n $table_vertical_separator
let "ci+=1"
done
echo ""
if [ ! -z "$recurse" ]
then
write_row "${remaining_cols[@]}"
fi
}
make_table() {
write_separate_line
write_row "col1" "col2" "col3"
write_separate_line
write_row "val1" "val3" "val4"
write_separate_line
write_row "valqeefnkl1" "val3wekjbkjwvsajbvjwsvbjbwvjkbjwdvbjwevbwjvbvwkjvjkvsbj" "val4"
write_separate_line
}
make_table
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment