展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

shell printf命令

  • 打印字符串
[root@VM-12-15-centos home]# printf "Hello, Shell\n"
Hello, Shell
  • 编写脚本
[root@VM-12-15-centos home]# vi test.sh
# 编写如下
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

# 执行
[root@VM-12-15-centos home]# sh test.sh
姓名     性别   体重kg
郭靖     男      66.12
杨过     男      48.65
郭芙     女      47.99

# 脚本说明
%s %c %d %f 都是格式替代符,%s 输出一个字符串,%d 整型输出,%c 输出一个字符,%f 输出实数,以小数形式输出。
%-10s 指一个宽度为 10 个字符(- 表示左对齐,没有则表示右对齐),任何字符都会被显示在 10 个字符宽的字符内,如果不足则自动以空格填充,超过也会将内容全部显示出来。
%-4.2f 指格式化为小数,其中 .2 指保留 2 位小数
替代符 说明
%s 字符串
%d 十进制整数
%f 浮点数
%c 字符
%x 十六进制数
%o 八进制数
%b 二进制数
%e 科学计数法表示的浮点数
  • 案例
# 双引号
[root@VM-12-15-centos home]# printf "%d %s\n" 1 "abc"
1 abc

# 单引号
[root@VM-12-15-centos home]# printf '%d %s\n' 1 "abc"
1 abc

# 没有引号
[root@VM-12-15-centos home]# printf %s abcdef
abcdef

# 指定1个参数
[root@VM-12-15-centos home]# printf %s abc def
abcdef

# 换行
[root@VM-12-15-centos home]# printf "%s\n" abc def
abc
def

# 用前面的三个参数a、b、c来替换这三个 %s 占位符,当没有足够的参数来填充所有的 %s 占位符时,printf 会按照给定的格式继续打印
[root@VM-12-15-centos home]# printf "%s %s %s\n" a b c d e f g h i j
a b c
d e f
g h i
j

# %s用NULL代替,%d用0代替
[root@VM-12-15-centos home]# printf "%s and %d \n"
 and 0
  • 转义序列
序列 说明
\a 警告字符,通常为ASCII的BEL字符
\b 后退
\c 抑制(不显示)输出结果中任何结尾的换行字符(只在%b格式指示符控制下的参数字符串中有效),而且,任何留在参数里的字符、任何接下来的参数以及任何留在格式字符串中的字符,都被忽略
\f 换页(formfeed)
\n 换行
\r 回车(Carriage return)
\t 水平制表符
\v 垂直制表符
\ 一个字面上的反斜杠字符
\ddd 表示1到3位数八进制值的字符。仅在格式字符串中有效
\0ddd 表示1到3位的八进制值字符
  • 案例
[root@VM-12-15-centos home]# printf "goudan \a"
goudan [root@VM-12-15-centos home]# 

[root@VM-12-15-centos home]# printf "goudan \b"
goudan[root@VM-12-15-centos home]# 

[root@VM-12-15-centos home]# printf "goudan \c"
goudan \c[root@VM-12-15-centos home]#

[root@VM-12-15-centos home]# printf "goudan \f"
goudan
       [root@VM-12-15-centos home]#
posted @ 2024-05-14 10:35  DogLeftover  阅读(1)  评论(0编辑  收藏  举报