How do I specify the position of a width parameter?

Viewed 127

Apologies if this has been posted before. I've been searching all over and can't find an answer.

According to man printf, "FORMAT controls the output as in C printf." It refers to printf(3).

According to man 3 printf, you can specify a variable width in a given position. It says:

Instead of a decimal digit string one may write … "*m$" (for some decimal integer m) to specify that the precision is given in the m-th argument … which must be of type int.

This is the part where I'm struggling. To give a simple example, suppose I wish to print a string with width 14.

$ printf '[%14s]\n' Something
[     Something]

I can use a variable instead:

$ WIDTH=14
$ printf '[%*s]\n' ${WIDTH} Something
[     Something]

The tricky part comes when I want to tell printf that the width argument is in a different position. To keep things simple for this example, I'll leave it where it is, in position 1. Following the instructions, I write the following.

Built-in version:

$ printf '[%*1$s]\n' ${WIDTH} Something
bash: printf: `1': invalid format character

Version in /usr/bin:

$ /usr/bin/printf '[%*1$s]\n' ${WIDTH} Something
[/usr/bin/printf: %*1: invalid conversion specification

Even using the example from the manual gives an error.

Built-in version:

$ printf '%2$*1$d' 6 34
bash: printf: `$': invalid format character

Version in /usr/bin:

$ /usr/bin/printf '%2$*1$d' 6 34
/usr/bin/printf: %2$: invalid conversion specification

As you can see, I get an error every time. I have struggled to see what I'm doing wrong, and I simply cannot find any example online.

How should this be formatted, please, or is the manual just wrong?

  • Lubuntu 18.04
  • GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu)
  • builtin printf: unknown version
  • /usr/bin/printf printf (GNU coreutils) 8.28

Thank you

2 Answers

No, the extension that comes from Single UNIX Specification to C printf function to specify the position of positional parameter with $ is not supported in bash printf and I doubt it's supported in any of shells printf implementations. I believe the reason is that it requires additional work from the developers, while it's very rarely used extension.

is the manual just wrong?

FORMAT controls the output as in C printf.

You are reading the documentation for GNU version of printf, taken from the amazing Linux man-pages project. I would say C printf is documented in the C standard.

If your shell's printf doesn't support parameter indexing, you can still call Perl to the rescue!

$ perl -we 'printf q([%1$*2$d]), @ARGV' 36 6
[    36]

See printf and, more importantly, sprintf.

Related