以格式化的方式获取输出

以格式化的方式获取输出

for循环中,我使用以下命令:

echo " Job_time is $i : Stopping the job "

示例输出:

Job_time is 6 : Stopping the job
Job_time is 6.50 : Stopping the job

期望的输出:

Job_time is 6    : Stopping the job
Job_time is 6.50 : Stopping the job

答案1

echo您可以使用printf来指定某些字段的宽度,而不是。对于给定的示例,替换

echo " Job_time is $i : Stopping the job "

printf ' Job_time is %-4s : Stopping the job \n' "$i"

因为$i显然是一个具有不同长度的字符串。如果它始终是有效的浮点数,您可以使用数字格式并显示printf尾随零:

printf ' Job_time is %4.2f : Stopping the job \n' "$i"

例如,

Job_time is 6.00 : Stopping the job
Job_time is 6.50 : Stopping the job

进一步阅读:

答案2

stopping the job始终从第 14 列开始打印

for ((i=0; i<100; i++))
do
    local offset=14
    printf "%s%*s\n" "Job_time is $i" $offset ": Stopping the job"

done

相关内容