printf %s%s one two
prints onetwo
but I would like oneonetwotwo
How can I do that?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityIn 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.
/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.
May 4 at 14:01
printf()
, it's standard (POSIX at least, not sure of C standard), I should probably make it clear.
May 4 at 14:45