The printf command
The printf command prints text in an exact format…
The printf command prints text in an exact format: printf "%s is %d\n" Ada 36 fills in a word and a number, and a new line comes only where you write \n.
A practice shell in your browser that behaves like bash on Linux for these commands. Nothing you type leaves the page.
Usage
printf FORMAT [ARGUMENT]...
Print formatted text. printf prints its FORMAT, replacing each % code with the next argument, and repeats the format while arguments are left. Unlike echo it adds no newline by itself, so put \n where you want one. %s is text, %d a whole number, %f a decimal (%.2f for two places), %x hexadecimal, %5s pads to 5 characters on the left and %-5s on the right, %05d pads a number with zeros, and %% is a percent sign.
How to use printf
Fill in text and numbers
%s is text, %d a whole number and %f a decimal. End the format with \n for a new line.
printf "%s is %d years old\n" Ada 36Ada is 36 years old
Line up columns
%-10s pads text to 10 characters, lined up on the left; %5d pads a number, lined up on the right.
printf "%-10s|%5d|\n" apples 12 pears 7apples | 12| pears | 7|
Decimals and leading zeros
%.2f keeps two decimals and %03d pads with zeros.
printf "%.2f\n" 3.141593.14
printf "%03d\n" 7007
One line for each argument
The format repeats until the arguments run out.
printf "%s\n" one two threeone two three
Save it in a variable: printf -v
printf -v id "%03d" 7echo "file-$id.txt"file-007.txt
Options
| -v NAME | put the result in a variable instead of printing it |
|---|
More examples
printf "%-8s|%5.1f\n" price 3.14159price | 3.1
Questions about printf
What is the difference between printf and echo?
echo prints its words and a new line, and its options differ between systems. printf prints exactly the format you give it, the same everywhere, so scripts that care about their output use it.
Why doesn’t printf print a new line?
It prints only what the format says. End the format with \n.
How do I print a % sign with printf?
Write %% in the format: printf "100%%\n".
Related commands
Every everyday command on one page, to print or keep open: the Linux commands cheat sheet.