可变长度未知的水平和垂直线间距

可变长度未知的水平和垂直线间距

我试图用特定格式打印一个输出,其中输出放在一个封闭的框中。
我用“”和“-”来创建它。我在“”之间打印的输出是具有不同字符数的变量。
这弄乱了我的格式。
我试过下面的代码

nodename=$(hostname)
cpu=$(cat /proc/cpuinfo | awk '/^processor/{print $3}' | wc -l)
echo " ------------------------------------------------------------------"
echo "|                                                                  |"
echo "|          This is Bash Scripting                                  |"
echo "|                                                                  |"
echo "|  1 - This Machine Name is $nodename                              |"
echo "|  2 - This Machine has $cpu CPU's                                 |"
echo "|                                                                  |"
echo " -------------------------------------------------------------------"

实际结果
" ------------------------------------------------------------------"
"|                                                                  |"
"|          This is Bash Scripting                                  |"
"|                                                                  |"
"|  1 - This Machine Name is test                              |"
"|  2 - This Machine has 8 CPU's                                 |"
"|                                                                  |"
" -------------------------------------------------------------------"

预期结果
" ------------------------------------------------------------------"
"|                                                                  |"
"|          This is Bash Scripting                                  |"
"|                                                                  |"
"|  1 - This Machine Name is test                                   |"
"|  2 - This Machine has 8 CPU's                                    |"
"|                                                                  |"
" -------------------------------------------------------------------"

最佳答案

使用printf而不是echo

printf "|  1 - This Machine Name is %-39s|\n" "$nodename"

您可以使用%-39s指定右空格填充。

关于linux - 可变长度未知的水平和垂直线间距,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57627132/

10-10 14:08