bash Shell 脚本输出格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37199283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:37:47  来源:igfitidea点击:

Shell Script output formatting

bashunixformat

提问by Vijay

I have output from a shell script like below

我有一个 shell 脚本的输出,如下所示

output1        ..... 1
output2     ..... 2
output3                 ............3

I tried to format it with equal spacing inside script but output still not have uniform spacing.

我试图在脚本内以相等的间距格式化它,但输出仍然没有统一的间距。

I want to print the output like below.

我想打印如下输出。

output1         ..... 1
output2         ..... 2
output3         ......3

Are there any commnads available to get this done. I use bash.

是否有任何可用的命令来完成此操作。我使用 bash。

here is the code.

这是代码。

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"

-Thanks.

-谢谢。

回答by John1024

The idea of printfis that you specify a format string that specifies column widths, etc:

想法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"

The first directive in the format string, %-40s, is applied to the first argument that follows the format string. It tells printf to display that argument in a 40-character-wide column. If we had used %40s, it would be a right-aligned column. I specified %-40sso that it would be left-aligned.

格式字符串中的第一个指令应用于格式字符串%-40s后面的第一个参数。它告诉 printf 在 40 个字符宽的列中显示该参数。如果我们使用了%40s,它将是一个右对齐的列。我指定%-40s它是左对齐的。

This produces output like:

这会产生如下输出:

$ 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

Documentation

文档

Bash's printfcommand is similar to printfin other languages, particularly the C version. Details specific to bash are found in man bash. Detailed information about the available format options is found in man 3 printf. To begin, however, you are probably better served by a tutorial such as this oneor this oneor this one.

Bash 的printf命令类似于printf其他语言,尤其是 C 版本。特定于 bash 的详细信息可以在man bash. 有关可用格式选项的详细信息可在 中找到man 3 printf。但是,一开始,您可能更适合阅读诸如this onethis onethis one 之类的教程。