Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 549
nedned Avatar asked Jun 15 '09 04:06

nedned


2 Answers

For bash, use the printf command with alignment flags.

For example:

printf '%7s' 'hello' 

Prints:

  hello 

(Imagine 2 spaces there)

Now, use your discretion for your problem.

like image 176
SuPra Avatar answered Sep 21 '22 22:09

SuPra


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 ... 
like image 43
Dennis Williamson Avatar answered Sep 21 '22 22:09

Dennis Williamson