printf

Last edit

Summary: minor rewording

Changed:

< The **printf** function is [[variadic]] and provides generic [[string formatting]] facilities. This enables output of formatted strings to a [[filehandle]] or to [[standard output]] in a similar manner to the printf function used in the C programming language. The printf function uses the same string formatting functions as [[sprintf]], but printf does not automatically append an [[output record separator]] or [[newline]] character to its output.

to

> The **printf** [[variadic]] function provides generic [[string formatting]] facilities. This enables output of formatted strings to a [[filehandle]] or to [[standard output]] in a similar manner to the printf function used in the C programming language. The printf function uses the same string formatting functions as [[sprintf]], but printf does not automatically append an [[output record separator]] or [[newline]] character to its output.


Usage

printf [ FORMAT, LIST ]

The printf [[variadic?]] function provides generic [[string_formatting?]] facilities. This enables output of formatted strings to a [[filehandle?]] or to [[standard_output?]] in a similar manner to the printf function used in the C programming language. The printf function uses the same string formatting functions as [[sprintf?]], but printf does not automatically append an [[output_record_separator?]] or [[newline?]] character to its output.

The printf function provides support for the complete set of ANSI C format specifications together with the %c, %d, %e, %E, %f, %g, %G, %i, %o, %s, %u, %x, %X and %% [[conversion_specifier?]]s, and the h and l [[conversion_qualifier?]]s.

The argument list to printf can optionally be enclosed in parentheses.

Example Usage

Print all the words on each line:

awk '{for(i=1;i<=NF;++i) printf "%s ", $i;print ""}' filename

Do NOT print the first word on each line:

awk '{for(i=2;i<=NF;++i) printf "%s ", $i;print ""}' filename

Print 3rd to 5th words in each line:

awk -v start=3 -v end=5 '{ for(i=start;i<=end;i++) printf "%s ", $i;print "" }' filename

Print the first to the eighth word on each line:

awk '{ i=0; while(++i<8) printf("%s ", $i); print $i }' filename

Delete all newline characters in a file:

awk '{printf "%s ",$O}' filename

Print entire file as an array:

awk '{delete a;}{for(i=1;i<=NF;++i) a[i]=$i} { for (j in a) printf("%s ",a[j]); print ""}' filename

Remember to always use a proper format string with printf, otherwise you can have some surprises, especially where you are printing arbitrary strings with unknown content:

echo "foo%d%sbar" | awk '{printf $0}' # error!
echo "foo%d%sbar" | awk '{printf "%s", $0}' # works