在 bash 中右对齐/填充数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/994461/
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 18:16:42  来源:igfitidea点击:

right align/pad numbers in bash

bashformatting

提问by nedned

What's the best way to pad numbers when printing output in bash, such that the numbers are right aligned down the screen. So this:

在 bash 中打印输出时填充数字的最佳方法是什么,以便数字在屏幕上右对齐。所以这:

00364.txt with 28 words in 0m0.927s
00366.txt with 105 words in 0m2.422s
00367.txt with 168 words in 0m3.292s
00368.txt with 1515 words in 0m27.238

Should be printed like this:

应该像这样打印:

00364.txt with   28 words in 0m0.927s
00366.txt with  105 words in 0m2.422s
00367.txt with  168 words in 0m3.292s
00368.txt with 1515 words in 0m27.238

I'm printing these out line by line from within a for loop. And I will know the upper bound on the number of words in a file (just not right now).

我从 for 循环中一行一行地打印出来。而且我会知道文件中字数的上限(只是现在不是)。

回答by Suvesh Pratapa

For bash, use the printfcommand with alignment flags.

对于 bash,使用printf带有对齐标志的命令。

For example:

例如:

 printf '%7s' 'hello'

Prints:

印刷:

   hello

(Imagine 2 spaces there)

(想象那里有 2 个空格)

Now, use your discretion for your problem.

现在,用你的判断力来解决你的问题。

回答by Paused until further notice.

Here's a little bit clearer example:

这是一个更清晰的例子:

#!/bin/bash
for i in 21 137 1517
do
    printf "...%5d ...\n" "$i"
done

Produces:

产生:

...   21 ...
...  137 ...
... 1517 ...

回答by test30

If you are interested in changing width dynamically, you can use printf's '%*s' feature

如果您对动态更改宽度感兴趣,可以使用 printf 的 '%*s' 功能

printf '%*s' 20 hello

which prints

哪个打印

               hello

回答by Jonathan Cross

Here is a combination of answers above which removes the hard-coded string length of 5characters:

这是上述答案的组合,删除了5字符的硬编码字符串长度:

VALUES=( 21 137 1517 2121567251672561 )
MAX=1

# Calculate the length of the longest item in VALUES
for i in "${VALUES[@]}"; do
  [ ${#i} -gt ${MAX} ] && MAX=${#i}
done

for i in "${VALUES[@]}"; do
  printf "... %*s ...\n" $MAX "$i"
done

Result:

结果:

...               21 ...
...              137 ...
...             1517 ...
... 2121567251672561 ...