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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:34:11  来源:igfitidea点击:

How to left justify text in bash?

bashprintfjustifytext-justify

提问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 printfcommand, like this:

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

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

The %smeans to interpret the argument as string, and the -10tells it to left justify to width 10 (negative numbers mean left justify while positive numbers justify to the right). The \nis required to print a newline, since printfdoesn't add one implicitly.

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

Notethat man printfbriefly 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 - flagfor left justification.

您可以使用- flagfor 左对齐。

Example:

例子:

[jaypal:~] printf "%10s\n" $txt
     hello
[jaypal:~] printf "%-10s\n" $txt
hello    

回答by SiegeX

bashcontains a printfbuiltin

bash包含一个printf内置

txt=1234567890
printf "%-10s\n" "$txt"