Name

printf

Synopsis

    printf format [val ...]

Not ksh88. Formatted printing, like the ANSI C printf function.

Additional Format Letters

Both Bash and ksh93 accept additional format letters. Bash only provides %b and %q, while ksh93 provides all those in the following list.

%b

Expand escape sequences in strings (e.g., \t to tab, and so on).

%B

The corresponding argument is a variable name (typically created via typeset -b); its value is retrieved and printed.

%d

An additional period and the output base can follow the precision (e.g., %5.3.6d to produce output in base 6).

%H

Output strings in HTML/XML format. (Spaces become &nbsp; and < and > become &lt; and &gt;.)

%n

Place the number of characters printed so far into the named variable.

%P

Translate egrep extended regular expression into ksh pattern.

%q

Print a quoted string that can be reread later on.

%R

Reverse of %P: translate ksh pattern into egrep extended regular expression.

%( format )T

Print a string representing a date and time according to the strftime(3) format format. The parentheses are entered literally. See the Examples.

%Z

Print an ASCII NUL (8 zero bits).

Examples

$ date                                  
                     Reformat date/time
    Tue Sep  7 15:39:42 EDT 2004
    $ printf "%(It is now %m/%d/%Y %H:%M:%S)T\n" "$(date)"
    It is now 09/07/2004 15:40:10

    $ printf "%H\n" "Here is a <string>"    
                     Convert to HTML
    Here&nbsp;is&nbsp;a&nbsp;&lt;string&gt;

Get Unix in a Nutshell, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.