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

2
  • Maybe this will help you : How to trim whitespace from bash variable ? Commented May 7, 2014 at 21:28
  • @Martin "your print statement" | tr -s ' ' ' ' Check if this works Commented May 7, 2014 at 22:19

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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?
Answer updated. It would have been helpful to show more than a single line of sample input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.