&sprintf(4)&sprintf - Formatted string construction
&sprintf format args
The &sprintf function (or &spr in it's abbreviated form) provides a mechanism to generated a formatted string, similar to the 'C' programming language sprintf(2) function.
The &sprintf function is generally used where a number of different sources of information have to be converted and joined together to form a new string. It is possible to do this using &cat(4), but it does become complicated if the number of strings to be spliced together is greater than about 4, sprintf alleviates these problems and results in faster execution. Where only two, or three strings are to be concatenated &cat provides better execution times.
The &sprintf function produces a string construct for the format and a caller determined number of arguments args (variable arguments). The format string may contain special '%' formatting commands to insert strings and numbers into the base format string. The format for the '%' commands is "%nc" where:
n
c
d (Decimal integer)
e (floating point number - scientific)
f (floating point number)
g (floating point number - shorter of e or f)
n (Repeat String)
o (Octal integer)
s (String)
x (Hexadecimal integer)
X (Hexadecimal integer)
%
The &sprintf function may be nested (i.e. a string argument to &sprintf may be the result of another &sprintf invocation). Although this type of construct is not generally required !!
The following examples show how the command may be used:
set-variable %result &sprintf "Foo [%s%s]" "a" "b"
generates "Foo [ab]"
set-variable %result &sprintf "Foo [%n%s]" 10 "a" "b"
generates "Foo [aaaaaaaaaab]".
set-variable %result &sprintf "[%d] [%3d] [%x] [%3x]" 10 11 12 13
generates "[10] [ 11] [c] [ d]"
It is the callers responsibility to ensure that the correct number of arguments is supplied to match the requested formatting string. The results are undefined if an incorrect number of arguments are supplied.
An error will be thrown if the % command is not one of the supported ones listed above.
Prior to August 2026 the s command treated n as a repeat count rather than a field width, so "%13s" inserted the string thirteen times. Macros written against the older behaviour must be changed to use the n command, which is unaffected:
; before - inserted the box character 13 times set-variable %line &sprintf "%13s" %box-char ; now set-variable %line &sprintf "%n" 13 %box-char
A "%" followed by digits and an "s" is the construct to look for.
Ref: &sprintf(4) File: m4fil004.4 Date: 2026/08/07
(c) Copyright JASSPA 2026