我有一个shell脚本的输出,如下所示
output1 ..... 1
output2 ..... 2
output3 ............3
Run Code Online (Sandbox Code Playgroud)
我尝试在脚本内以相等的间距格式化它,但输出仍然没有统一的间距.
我想打印输出如下.
output1 ..... 1
output2 ..... 2
output3 ......3
Run Code Online (Sandbox Code Playgroud)
是否有任何通讯可以完成这项工作.我用bash.
这是代码.
lnode=abc
printf "server name ......... "$lnode""
printf "\nserver uptime and load details : ......... `uptime`"
printf "\n"
lcpu=`cat /proc/cpuinfo | grep -i process |wc -l`
printf "Total number of CPUs on this server : ......... $lcpu\n"
Run Code Online (Sandbox Code Playgroud)
-谢谢.
想法printf
是指定一个指定列宽等的格式字符串:
$ cat script.sh
lnode=abc
printf "%-40s %s\n" "server name :" "......... $lnode"
printf "%-40s %s\n" "server uptime and load details :" "......... `uptime`"
lcpu=$(cat /proc/cpuinfo | grep -i process |wc -l)
printf "%-40s %s\n" "Total number of CPUs on this server :" "......... $lcpu"
Run Code Online (Sandbox Code Playgroud)
格式字符串中的第一个指令应用于格式字符串%-40s
后面的第一个参数.它告诉printf在40个字符宽的列中显示该参数.如果我们使用过%40s
,它将是一个右对齐的列.我指定%-40s
它将左对齐.
这会产生如下输出:
$ bash script.sh
server name : ......... abc
server uptime and load details : ......... 18:05:50 up 17 days, 20 users, load average: 0.05, 0.20, 0.33
Total number of CPUs on this server : ......... 4
Run Code Online (Sandbox Code Playgroud)
Bash的printf
命令与printf
其他语言类似,尤其是C版本.有关bash的详细信息,请参阅man bash
.有关可用格式选项的详细信息,请参阅man 3 printf
.首先,然而,你可能更好地补习服务,如这一个或这一个或这一个.