views:

1392

answers:

3

What's the best way to pad numbers when printing output in bash, such that the numbers are right aligned down the screen. So this:

00364.txt with 28 words in 0m0.927s
00366.txt with 105 words in 0m2.422s
00367.txt with 168 words in 0m3.292s
00368.txt with 1515 words in 0m27.238

Should be printed like this:

00364.txt with   28 words in 0m0.927s
00366.txt with  105 words in 0m2.422s
00367.txt with  168 words in 0m3.292s
00368.txt with 1515 words in 0m27.238

I'm printing these out line by line from within a for loop. And I will know the upper bound on the number of words in a file (just not right now).

A: 

I would use printf(1) (that's the shell program printf, not the C function printf, although they do the same thing.) I think it has a code for right-aligning numbers, though I forget what it is at the moment.

David Zaslavsky
+4  A: 

Use the printf command for bash, and use alignment flags.

As an example,

 printf '%7s' 'hello'

prints:

   hello

(Imagine 2 spaces there)

Now use your discretion for your problem.

Suvesh Pratapa
Wow, ok that was pretty easy. I should have just RTFM. I guess I just incorrectly assumed it would be harder than that in bash. Thanks!
humble coffee
A: 

Here's a little bit clearer example:

#!/bin/bash
for i in 21 137 1517
do
    printf "...%5s ...\n" $i
done

Produces:

...   21 ...
...  137 ...
... 1517 ...
Dennis Williamson