如何在 bash 中打印一些文本并用空格填充到特定宽度? [英] How do I print some text in bash and pad it with spaces to a certain width?

查看:27
本文介绍了如何在 bash 中打印一些文本并用空格填充到特定宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在带有变量的 bash 脚本中回显一些文本,并希望填充该变量,以便它始终在右侧有适当数量的空格以保持文本的其余部分对齐.

I'm echoing some text in a bash script with a variable in it, and want to pad that variable so it will always have the appropriate ammount of spaces to the right to keep the rest of the text aligned.

这是我想要的示例:

Echoing random number 1080    [ OK ]
Echoing random number 443     [ OK ]
Echoing random number 34842   [ OK ]

数值的长度会有所不同(可能不超过 5 或 6 位).

The numerical value would be of varying length (probably no longer than 5 or 6 digits).

我知道 printf 可以做到这一点,并通过执行以下操作来正确对齐变量:

I know that printf can do this and right align the variable by doing the following:

printf "Echoing random number %5s   [ OK ]" $RAND_NUM

然而,这会像这样格式化文本:

However, this would format the text like this:

Echoing random number  1080   [ OK ]
Echoing random number   443   [ OK ]
Echoing random number 34842   [ OK ]

当然,只是用空格回声是行不通的:

And of course just echoing with spaces doens't work:

echo "Echoing random number ${RAND_NUM}   [ OK ]"

产生这个:

Echoing random number 1080   [ OK ]
Echoing random number 443   [ OK ]
Echoing random number 34842   [ OK ]

有没有办法像我的第一个例子一样打印文本?

Is there a way to print the text like my first example?

推荐答案

使用 - 来左对齐一个字段.

Use - to left align a field.

printf "Echoing random number %-5s   [ OK ]" $RAND_NUM

或者,如果您使用的是 Red Hat Linux 系统,则有一些预定义的函数会打印出绿色 OK 和红色 FAILED 提示(您在启动期间看到的提示):

Alternatively, if you're on a Red Hat Linux system there are predefined functions that will print out green OK and red FAILED prompts (the ones you see during bootup):

#!/bin/bash

. /etc/init.d/functions

echo -n "Frobbing widget:"
frob_widget && echo_success || echo_failure
echo

这篇关于如何在 bash 中打印一些文本并用空格填充到特定宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆