bash 如何在bash中左对齐文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8994108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to left justify text in bash?
提问by Misha Moroshko
Given a text, $txt
, how could I left justify it to a given width in Bash.
给定一个文本,$txt
我怎么能在 Bash 中将它对齐到给定的宽度。
Example (width = 10):
示例(宽度 = 10):
If $txt=hello
, I would like to print:
如果$txt=hello
,我想打印:
hello |
If $txt=1234567890
, I would like to print:
如果$txt=1234567890
,我想打印:
1234567890|
回答by drrlvn
You can use the printf
command, like this:
您可以使用该printf
命令,如下所示:
printf "%-10s |\n" "$txt"
The %s
means to interpret the argument as string, and the -10
tells it to left justify to width 10 (negative numbers mean left justify while positive numbers justify to the right). The \n
is required to print a newline, since printf
doesn't add one implicitly.
将%s
参数解释为字符串的方法,并-10
告诉它左对齐宽度为 10(负数表示左对齐,正数右对齐)。在\n
需要打印一个换行符,因为printf
不添加一个含蓄。
Notethat man printf
briefly describes this command, but the fullformat documentation can be found in the C function man page in man 3 printf
.
请注意,man printf
简要描述了此命令,但完整格式的文档可以在man 3 printf
.
回答by jaypal singh
You can use the - flag
for left justification.
您可以使用- flag
for 左对齐。
Example:
例子:
[jaypal:~] printf "%10s\n" $txt
hello
[jaypal:~] printf "%-10s\n" $txt
hello
回答by SiegeX
bash
contains a printf
builtin
bash
包含一个printf
内置
txt=1234567890
printf "%-10s\n" "$txt"