'right align/pad numbers in bash

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).



Solution 1:[1]

Here's a little bit clearer example:

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

Produces:

...   21 ...
...  137 ...
... 1517 ...

Solution 2:[2]

If you are interested in changing width dynamically, you can use printf's '%*s' feature

printf '%*s' 20 hello

which prints

               hello

Solution 3:[3]

Here is a combination of answers above which removes the hard-coded string length of 5 characters:

VALUES=( 21 137 1517 2121567251672561 )
MAX=1

# Calculate the length of the longest item in VALUES
for i in "${VALUES[@]}"; do
  [ ${#i} -gt ${MAX} ] && MAX=${#i}
done

for i in "${VALUES[@]}"; do
  printf "... %*s ...\n" $MAX "$i"
done

Result:

...               21 ...
...              137 ...
...             1517 ...
... 2121567251672561 ...

Solution 4:[4]

If you happen to get the number to be formatted from output of another script and you wish to pipe this result to be right align, just utilize xargs:

ls -1 | wc -l | xargs printf "%7d"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 test30
Solution 3
Solution 4 Thomas Urban