5

printf %s%s one two prints onetwo but I would like oneonetwotwo

How can I do that?

1 Answer 1

8

In zsh:

printf '%1$s%1$s' one two

Where %n$s is like %s except that it uses the nth argument instead of the next one like the printf()¹ of the GNU libc (but not in the standalone GNU printf utility nor the printf builtin of the GNU shell (bash) yet).

That was added to zsh in 2001 and is also available in a few other printf implementations though with some variations and will be specified in the next version of the POSIX standard

Note that while printf '%s%1$s' one two would also work in zsh, it does not in all printf implementations that support %n$x and POSIX will make the behaviour unspecified if directives with and without n$ are mixed.

Another option is to use the array zipping operator, for instance in an anonymous function:

(){ printf %s%s ${argv:^argv}; } one two

Where with zip $argv with itself resulting in one one two two being passed to printf. As usual, change to "${(@)argv:^argv}" or "${@:^argv}" to preserve empty elements in any.


That %$nX syntax in printf() is POSIX, possibly originating in SVR4 (was in SVR4, not SVR3), probably coming from nl_printf() earlier used for localisation of messages where the order of elements in a message may change from one language to the next.

3
  • Probably it should be noted that the feature was intended to help localizations originally, so using it to duplicate an argument on output is just a special case.
    – U. Windl
    Commented May 4, 2023 at 7:40
  • /usr/bin/printf and the BSD libc function in MacOS support this. This is fun: /usr/bin/printf '%1$s%0$s' one two (zero is an undefined argument index). It outputs one%1$s%0$stwoone - don't use zero in both positions, it outputs the format string repeatedly forever (^C interrupts). Zero causes an error to be output in zsh. Commented May 4, 2023 at 14:01
  • @DennisWilliamson, from printf(), it's standard (POSIX at least, not sure of C standard), I should probably make it clear. Commented May 4, 2023 at 14:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .