Question

I can print my array elemets using echo in a loop, but the output format is really bad . there I tried injecting tab but there is just a lot of spaces between the elements ssince each element length is different. I have no idea how to use printf ? I tried , but it just not working properly. is there a way to format my printf or echo so I have equal number of spaces between each element? This is driving me mad.

while [[ $counter -lt $nai ]];
do
#echo ${slist[$counter]} $'\t' ${sstate[$counter]} $'\t' $'\t' ${scached[$counter]}
printf ${slist[$counter]} $'\t' ${sstate[$counter]} $'\t' $'\t' ${scached[$counter]}
counter=$(( $counter + 1 ))
done

IN short I just want to print my elements in a format with equal number of spaces between the elements like this

  abc  cdf  efg

What i'm getting is

  abc       cdf            efg

Thanks

Was it helpful?

Solution

If you want to print elements with N spaces between them, you can use printf:

a="foo"
b="somestring"
c="bar"

# Print each argument with three spaces between them
printf "%s   " "$a" "$b" "$c"
# Print a line feed afterwards
printf "\n"

This results in:

foo   somestring   bar
otherdata   foo   bar

You can also use the format %-12s to pad each element to 12 character:

# Pad each field to 12 characters
printf "%-12s" "$a" "$b" "$c"
printf "\n"

Resulting in:

foo         somestring  bar         
otherdata   foo         bar

OTHER TIPS

Try using a format string with printf

printf "%s  %s  %s\n" ${slist[$counter]} ${sstate[$counter]} ${scached[$counter]}

If the fields don't have whitespace, use column -t:

{
echo my dog has fleas
echo some random words here
} | column -t
my    dog     has    fleas
some  random  words  here

Or, in your case: while ...; do ...; done | column -t

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top