34

给定一个文本,$txt我怎么能在 Bash 中将其对齐到给定的宽度?

示例(宽度 = 10):

如果$txt=hello,我想打印:

hello     |

如果$txt=1234567890,我想打印:

1234567890|
4

3 回答 3

56

您可以使用该printf命令,如下所示:

printf "%-10s |\n" "$txt"

%s参数解释为字符串的方法,并-10告诉它左对齐到宽度 10(负数表示左对齐,而正数表示右对齐)。\n需要打印换行符,因为不会printf隐式添加。

请注意man printf简要描述了此命令,但完整格式的文档可以在 C 函数手册页中找到man 3 printf

于 2012-01-24T21:05:50.843 回答
5

您可以使用该-标志进行左对齐。

例子:

[jaypal:~] printf "%10s\n" $txt
     hello
[jaypal:~] printf "%-10s\n" $txt
hello
于 2012-01-24T21:06:40.403 回答
2

Bash 包含一个printf内置函数:

txt=1234567890
printf "%-10s\n" "$txt"
于 2012-01-24T21:06:06.193 回答