Atomiklan
Atomiklan

Reputation: 5434

printf column alignment issue

Can someone help me understand printf's alignment function. I have tried reading several examples on Stack and general Google results and I'm still having trouble understanding its syntax. Here is essentially what I'm trying to achieve:

HOLDING    1.1.1.1              Hostname        Potential outage!
SKIPPING   1:1:1:1:1:1:1:1      Hostname        Existing outage!

I'm sorry, I know this is more of a handout than my usual questions. I really don't know how to start here. I have tried using echo -e "\t" in the past which works for horizontal placement, but not alignment. I have also incorporated a much more complex tcup solution using a for loop, but this will not work easily in this situation.

I just discovered printf's capability though and it seems like it will do what I need, but I dont understand the syntax. Maybe something like this?

A="HOLDING"
B="1.1.1.1"
C="Hostname"
D="Potential outage"
for (( j=1; j<=10; j++ )); do 
  printf "%-10s" $A $B $C $D
  echo "\n"
done

Those variables would be fed in from a db though. I still dont really understand the printf syntax though? Please help

* ALSO *

Off topic question, what is your incentive for responding? I'm fairly new to stack exchange. Do some of you get anything out of it other than reputation. Careers 2.0? or something else? Some people have ridiculous stats on this site. Just curious what the drive is.

Upvotes: 1

Views: 161

Answers (1)

that other guy
that other guy

Reputation: 123450

The string %-10s can be broken up into multiple parts:

  • % introduces a conversion specifier, i.e. how to format an argument
  • - specifies that the field should be left aligned.
  • 10 specifies the field width
  • s specifies the data type, string.

Bash printf format strings mimic those of the C library function printf(3), and this part is described in man 3 printf.

Additionally, Bash printf, when given more arguments than conversion specifiers, will print the string multiple times for each argument, so that printf "%-10s" foo bar is equivalent to printf "%-10s" foo; printf "%-10s" bar. This is what lets you specify all the arguments on the same command, with the %-10s applying to each of them.

As for people's motivation, you could try the meta site, which is dedicated to questions about stackoverflow itself.

Upvotes: 2

Related Questions