I’m trying to print a CSV file using certain column widths. I think there’s an off by one error with i that’s causing the first column not to print. As you will see, I’m new to bash and desperately trying to make it act like C.
CSV='./test.csv'
column_width=(20 6 5 10 10 10 10 8 30)
IFS=","
while read LINE
do
set -- $LINE
arg=($@)
for (( i = 0 ; i < ${#arg[@]} ; i++))
do
case $i in
1) printf "%-20s" ${arg[$i]} ;;
2) printf "%-6s" ${arg[$i]} ;;
3) printf "%-5s" ${arg[$i]} ;;
4) printf "%-10s" ${arg[$i]} ;;
5) printf "%-10s" ${arg[$i]} ;;
6) printf "%-10s" ${arg[$i]} ;;
7) printf "%-10s" ${arg[$i]} ;;
8) printf "%-8s" ${arg[$i]} ;;
9) printf "%-30s\n" ${arg[$i]} ;;
esac
done
done < $CSV
unset IFS
I’m also having trouble turning the case statement into a loop. To no avail, I tried replacing the entire C-style for-loop with:
for i in "${arg[@]}"; do
printf "%-${column_width[$i]}s" ${arg[$i]}
done
I’m sure there’s a better way to accomplish this. I’m trying to learn about sed/awk but I’d like to know how to do it without them for now.
1 Answer