gawk: Printf Ordering
1
1 13.4.2 Rearranging 'printf' Arguments
1 -------------------------------------
1
1 Format strings for 'printf' and 'sprintf()' (⇒Printf) present a
1 special problem for translation. Consider the following:(1)
1
1 printf(_"String `%s' has %d characters\n",
1 string, length(string)))
1
1 A possible German translation for this might be:
1
1 "%d Zeichen lang ist die Zeichenkette `%s'\n"
1
1 The problem should be obvious: the order of the format specifications
1 is different from the original! Even though 'gettext()' can return the
1 translated string at runtime, it cannot change the argument order in the
1 call to 'printf'.
1
1 To solve this problem, 'printf' format specifiers may have an
1 additional optional element, which we call a "positional specifier".
1 For example:
1
1 "%2$d Zeichen lang ist die Zeichenkette `%1$s'\n"
1
1 Here, the positional specifier consists of an integer count, which
1 indicates which argument to use, and a '$'. Counts are one-based, and
1 the format string itself is _not_ included. Thus, in the following
1 example, 'string' is the first argument and 'length(string)' is the
1 second:
1
1 $ gawk 'BEGIN {
1 > string = "Don\47t Panic"
1 > printf "%2$d characters live in \"%1$s\"\n",
1 > string, length(string)
1 > }'
1 -| 11 characters live in "Don't Panic"
1
1 If present, positional specifiers come first in the format
1 specification, before the flags, the field width, and/or the precision.
1
1 Positional specifiers can be used with the dynamic field width and
1 precision capability:
1
1 $ gawk 'BEGIN {
1 > printf("%*.*s\n", 10, 20, "hello")
1 > printf("%3$*2$.*1$s\n", 20, 10, "hello")
1 > }'
1 -| hello
1 -| hello
1
1 NOTE: When using '*' with a positional specifier, the '*' comes
1 first, then the integer position, and then the '$'. This is
1 somewhat counterintuitive.
1
1 'gawk' does not allow you to mix regular format specifiers and those
1 with positional specifiers in the same string:
1
1 $ gawk 'BEGIN { printf "%d %3$s\n", 1, 2, "hi" }'
1 error-> gawk: cmd. line:1: fatal: must use `count$' on all formats or none
1
1 NOTE: There are some pathological cases that 'gawk' may fail to
1 diagnose. In such cases, the output may not be what you expect.
1 It's still a bad idea to try mixing them, even if 'gawk' doesn't
1 detect it.
1
1 Although positional specifiers can be used directly in 'awk'
1 programs, their primary purpose is to help in producing correct
1 translations of format strings into languages different from the one in
1 which the program is first written.
1
1 ---------- Footnotes ----------
1
1 (1) This example is borrowed from the GNU 'gettext' manual.
1