在bash中右对齐/填充数字

时间:2009-06-15 04:04:36

标签: bash formatting

在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

应该像这样打印:

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

我在for循环中逐行打印这些。我将知道文件中单词数量的上限(现在不是)。

5 个答案:

答案 0 :(得分:35)

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

例如:

 printf '%7s' 'hello'

打印:

   hello

(想象一下有两个空格)

现在,请根据您的问题自行决定。

答案 1 :(得分:22)

这里有一个更清晰的例子:

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

产地:

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

答案 2 :(得分:9)

如果您有兴趣动态更改宽度,可以使用printf'%* s'特征

printf '%*s' 20 hello

打印

               hello

答案 3 :(得分:3)

以上是上述答案的组合,删除了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

结果:

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

答案 4 :(得分:0)

如果您碰巧从另一个脚本的输出中获得要格式化的数字,并且希望通过管道将此结果正确对齐,只需使用 xargs

ls -1 | wc -l | xargs printf "%7d"