The best Shell printf command Tutorial In 2024, In this tutorial you can learn Printf's escape sequence,
The last chapter we learned Shell echo command, in this chapter we learn another output Shell command printf.
printf command imitate C library (library) in the printf () procedure.
Standard definition, so use printf script better than using echo portability.
printf using a reference text or parameters separated by spaces, can be used outside of the printf format string, you can also develop the width of the string, and so on left and right alignment. Default printf does not automatically add a line break like echo, we can add \ n manually.
printf command syntax:
printf format-string [arguments/en.]
Parameter Description:
Examples are as follows:
$ echo "Hello, Shell" Hello, Shell $ printf "Hello, Shell\n" Hello, Shell $
Next, I use a script to reflect the powerful printf:
#!/bin/bash # author:本教程 # url:www.w3write.com printf "%-10s %-8s %-4s\n" 姓名 性别 体重kg printf "%-10s %-8s %-4.2f\n" 郭靖 男 66.1234 printf "%-10s %-8s %-4.2f\n" 杨过 男 48.6543 printf "%-10s %-8s %-4.2f\n" 郭芙 女 47.9876
Execute the script, the output is as follows:
姓名 性别 体重kg 郭靖 男 66.12 杨过 男 48.65 郭芙 女 47.99
% S% c% d% f format are placeholders
% -10s Refer to a width of 10 characters (- for left-aligned, right-aligned, said no), any characters are displayed in 10 characters wide characters, if insufficient space is automatically filled in, it will be more than content show all of them.
% -4.2f Refers to decimal format, which means .2 2 decimal places.
More examples:
#!/bin/bash # author:本教程 # url:www.w3write.com # format-string为双引号 printf "%d %s\n" 1 "abc" # 单引号与双引号效果一样 printf '%d %s\n' 1 "abc" # 没有引号也可以输出 printf %s abcdef # 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用 printf %s abc def printf "%s\n" abc def printf "%s %s %s\n" a b c d e f g h i j # 如果没有 arguments,那么 %s 用NULL代替,%d 用 0 代替 printf "%s and %d \n"
Execute the script, the output is as follows:
1 abc 1 abc abcdefabcdefabc def a b c d e f g h i j and 0
sequence | Explanation |
---|---|
\ A | Warning character, usually the ASCII BEL character |
\ B | Retreat |
\ C | Inhibition (not shown) output in any trailing newline characters (valid only in the parameter string under the% b format indicator controlled), and, in any characters left in the parameters, and any parameters and any subsequent stay in format string characters are ignored |
\ F | FF (formfeed) |
\ N | Wrap |
\ R | Enter (Carriage return) |
\ T | Horizontal tab |
\ V | Vertical tab |
\\ | A literal backslash character |
\ Ddd | Represent characters 1-3 digit octal value. Valid only in the format string |
\ 0ddd | Showing 1-3 octal value of the character |
$ 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.w3write.com \a" www.w3write.com $ #不换行