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

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

问题描述

我在回响着一个bash脚本一些文字在它一个变量,要垫变量,因此总会有空格适当ammount的,以保持对齐文本的休息权。

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.

下面就是我想要的一个例子:

Here's an example of what I want:

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?

推荐答案

使用 - 左对齐字段

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

另外,如果你是一个Red Hat Linux系统上也有predefined功能,将打印出绿色的OK和红色失败提示(那些你在启动过程中看到的):

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天全站免登陆