[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: printf and the $ modifier
From: |
Chet Ramey |
Subject: |
Re: printf and the $ modifier |
Date: |
Fri, 19 Dec 2014 10:54:05 -0500 |
User-agent: |
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:24.0) Gecko/20100101 Thunderbird/24.6.0 |
On 12/19/14, 9:46 AM, Maarten Billemont wrote:
> man 3 printf describes the following:
>
> o An optional field, consisting of a decimal digit string followed
> by a $, specifying the next argument to access. If this field is not
> provided,
> the argument following the last argument accessed will be used.
> Arguments are numbered starting at 1. If unaccessed arguments in the format
> string are interspersed with ones that are accessed the results
> will be indeterminate.
>
> This is a useful feature, allowing you to decouple the order of your
> arguments with from the format. This is useful for localization and a few
> other cases. In this example, I'd like to use it to simplify a regex
> replace statement:
>
> # s/(.*)foo(.*)/$2bar$1/
> [[ 123foo567 =~ (.*)foo(.*) ]] && printf '%2$sbar%1$s' "${BASH_REMATCH[@]:1}"
>
> Is there a particular reason why bash's built-in printf does not support
> this format modifier? Does bash re-implement printf or does it use the
> Standard C Library's printf? (If the former; why?)
Several reasons:
1. Posix doesn't require it.
2. It doesn't mesh well with the argument-reuse and argument-
marshaling-for-printf requirements, especially since that modifier
has to be used for every argument or things don't work.
3. There's not actually a lot of demand to make it available, and few
implementations go through the pain (even the standalone GNU printf).
The only one I found after a quick non-exhaustive search is the ksh93
builtin, which doesn't use the libc printf engine at all.
Chet
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, ITS, CWRU chet@case.edu http://cnswww.cns.cwru.edu/~chet/