Shell Command Printf
In the previous chapter we learn the command echo, this chapter we will introduce the command printf.
Printf mimics the printf () program in the C library.
Printf is defined by the POSIX standard, so scripts that use printf are more portable than echo.
Printf uses parameters which are text in quoted form or space-separated, format string can be used in printf outside, and the width and left-right alignment of the string can also be specified.By default, printf does not add line breaks automatically like echo, we can add \ n manually.
The syntax of the command printf:
printf format-string [arguments...]
Parameters Description:
- format-string: string in format
- arguments: parameters list
For example
$ echo "Hello, Shell"
Hello, Shell
$ printf "Hello, Shell\n"
Hello, Shell
$
Next, the following script will reflect the printf powerful features:
#!/bin/bash
# author:ylspirit
# www.linuxcommands.site
printf "%-10s %-8s %-4s\n" Name Gender Weight(kg)
printf "%-10s %-8s %-4.2f\n" Carol male 66.1234
printf "%-10s %-8s %-4.2f\n" Lily female 48.6543
printf "%-10s %-8s %-4.2f\n" Lucy female 47.9876
Execute the script and output is
Name Gender Weight(kg)
Carol male 66.1234
Lily female 48.6543
Lucy female 47.9876
%s, %c,%d,%f are all format substitution characters
%-10s refers to a character with a width of 10 characters (-means left aligned, right means nothing), any character will be displayed within 10 characters wide, if not enough, it will be automatically filled with spaces, if exceeding, all content will be displayed.
%-4.2f means formatted as a decimal, where .2 means reserve 2 decimal places.
More examples:
#!/bin/bash
# author:ylspirit
# www.linuxcommands.site
# format-string double quotes
printf "%d %s\n" 1 "abc"
# Single quotes have the same effect as double quotes
printf '%d %s\n' 1 "abc"
# Without quotes also can be output
printf %s abcdef
# The format only specifies one parameter, but the extra parameters will still be output in this format, format-string is reused
printf %s abc def
printf "%s\n" abc def
printf "%s %s %s\n" a b c d e f g h i j
# If there are no arguments, %s is replaced by NULL and %d is replaced by 0
printf "%s and %d \n"
Execute the script and output is
1 abc
1 abc
abcdefabcdefabc
def
a b c
d e f
g h i
j
and 0
Printf escape sequence
Tag | Description |
---|---|
\a | alert (BEL),ASCII BEL character generally |
\b | backspace |
\c | produce no further output |
\f | form feed |
\n | new line |
\r | carriage return |
\t | horizontal tab |
\v | vertical tab |
\\ | backslash |
\ddd | character with octal value ddd (1 to 3 digits),only valid in format string |
\0ddd | character with octal value ddd (1 to 3 digits) |
For example
$ printf "a string, no processing:<%s>\n" "A\nB"
a string, no processing:<A\nB>
$ printf "a string, no processing:<%b>\n" "A\nB"
a string, no processing:<A
B>
$ printf "www.linuxcommands.site \a"
www.linuxcommands.site $ #Do not wrap