0

I have made a tabular report of some data variables printed via printf in shell.

Project One    | 76   | 80M    | 80M    | 80M 
Project Two    | 46M  | 52M    | 52M    | 52M 
Project Three  | 174  | 171M   | -      | 173M 

The output here is a manually spaced one. Is there a way to print variables that occupies fixed width?

For example, in the first row, 76[space], 80M, ... total of three character width with printing with a shell variable.

1 Answers1

0

If I understood what you want is a function to leave certain number of spaces after a specified string. Here it is:

fix_space() {
    string="$1"
    len="$2"
    perl -e "my \$str = '`printf "$string" | sed "s/'/\\'/g"`'; print \$str.' ' x ($len - length(\$str))"
}
echo "'`fix_space "ololfdsaf" 20`'"
echo "'`fix_space "ololff" 20`'"

It simply makes perl doing all the dirty job. String goes as the first argument, and the full length as the second. I am sure this will help you to align your output.

EDIT:

You can do it without perl with only using shell. Then you have to type:

printf "'$string`printf ' '%.0s {1..$((len - ${#string}))}`'\n"

Reference

http://rosettacode.org/wiki/Repeat_a_string#UNIX_Shell

theoden8
  • 640