1

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

theuniverseisflat
  • 861
  • 2
  • 12
  • 19
  • Maybe this will help you : [How to trim whitespace from bash variable ?](http://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-bash-variable) – Martin May 07 '14 at 21:28
  • @Martin `"your print statement" | tr -s ' ' ' '` Check if this works – PradyJord May 07 '14 at 22:19

2 Answers2

1

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

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Thanks its much better .. there is equal spacing .. but since the elements are not of equal length still they are not aligned properly. Is there a way to align them properly? – theuniverseisflat May 07 '14 at 21:40
  • Answer updated. It would have been helpful to show more than a single line of sample input. – glenn jackman May 07 '14 at 23:39
1

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
that other guy
  • 116,971
  • 11
  • 170
  • 194