代码之家  ›  专栏  ›  技术社区  ›  nedned

bash中的右对齐/填充编号

  •  22
  • nedned  · 技术社区  · 17 年前

    在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循环中逐行打印这些内容。我将知道文件中单词数的上限(只是现在还不知道)。

    4 回复  |  直到 17 年前
        1
  •  46
  •   Gabriel Staples    5 年前

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

    例如:

    printf '%7s' 'hello'
    

    印刷品:

      hello
    

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

        2
  •  26
  •   Dennis Williamson    14 年前

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

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

    ...   21 ...
    ...  137 ...
    ... 1517 ...
    
        3
  •  10
  •   test30    12 年前

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

    printf '%*s' 20 hello
    

    哪张照片

                   hello
    
        4
  •  5
  •   Jonathan Cross    8 年前

    下面是以上答案的组合,它删除了 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 ...
    
        5
  •  0
  •   Thomas Urban    5 年前

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

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