0

In Bash I can use printf to format a string output like this:- (Note how I've added a suffix of W to the string and that this is not included in the padding)

$ printf "Blah %11.1fW\n" 123 456 78965 5 56
Blah       123.0W
Blah       456.0W
Blah     78965.0W
Blah         5.0W
Blah        56.0W

If I want to prefix the string I could do this:-

$ printf "Blah £%11.1f\n" 123 456 78965 5 56
Blah £      123.0
Blah £      456.0
Blah £    78965.0
Blah £        5.0
Blah £       56.0

However note how this results in the padding being applied before the prefix.

How (if at all possible) would I use printf to prefix the value before padding so the output would be as follows:-

Blah      £ 123.0
Blah      £ 456.0
Blah    £ 78965.0
Blah        £ 5.0
Blah       £ 56.0

If not possible any Bash solution would be appropriate.

general exception
  • 4,202
  • 9
  • 54
  • 82

3 Answers3

4

I came up with this:

$ printf "Rate: %11s\n" $(printf "$%.1f " 12345 123)
Rate:    $12345.0
Rate:      $123.0

Just be sure the choose the correct %11s for your case.


It seems that you addressed that space problem yourself. For the sake of completeness, I will put that in here.

$ printf "Rate: %11s\n" $(printf "$%.1f " 12345 123) | sed 's/\$/\$ /g'
Rate:    $ 12345.0
Rate:      $ 123.0

Here's the solution given by @FatalError:

printf "Rate: %11b\n" $(printf '$\\0040%.1f ' 12345 123)
Rate:   $ 12345.0
Rate:     $ 123.0
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
3

Not possible. You'd need something like strfmon. Workaround:

$ a=(123 456 78965 5 56)
$ printf 'blah %*s %.1f\n' {,,,,}{$((10 - ${#a[n]})),£,"${a[n++]}"}
blah      £ 123.0
blah      £ 456.0
blah    £ 78965.0
blah        £ 5.0
blah       £ 56.0
ormaaj
  • 6,201
  • 29
  • 34
2

While I love ormaaj's solution for keeping things in the shell, I don't like using subshells unless I really need them. And a line with both a subshell AND a pipe just seems ... unnecessary.

$ printf "Rate: %11.1f\n" 123 | sed 's/  \([0-9]\)/$ \1/'
Rate:     $ 123.0
ghoti
  • 45,319
  • 8
  • 65
  • 104