21.5.15

Make lower triangle matrix from string using bash

This is sometimes useful for formatting a genetic distance matrix from input data of unspecified format. Yes, it is an ugly cludge.

val="1 2 3 4 5 6 7 8 9 10 11 12 13 14 15";
j=1; k=0; v=$(echo $val | wc -w | awk {'print $1'});
r=$(printf "%.0f" $(echo "sqrt(2*$v+(1/4))-(1/2)" | bc -l));
for ((i=1;i<=$r;i++));
do m=$(($j+$k));
j=$(($j+$k)); k=$(($k+1));
n=$(printf "%.0f" $(echo "($k+1)*($k/2)" | bc -l));
echo $val | cut -d' ' -f$m-$n;
done


1
2 3
4 5 6
7 8 9 10
11 12 13 14 15