如何在Bash中对齐表的列? [英] How can I align the columns of tables in Bash?

查看:75
本文介绍了如何在Bash中对齐表的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想输出表格格式的文本.我试图做的是用'\ t'回显数组的元素,但是它没有对齐.

I'd like to output a table format text. What I tried to do was echo the elements of an array with '\t', but it was misaligned.

我的代码

for((i=0;i<array_size;i++));
do
   echo stringarray[$i] $'\t' numberarray[$i] $'\t' anotherfieldarray[$i]
done;

我的输出

a very long string..........     112232432      anotherfield
a smaller string         123124343     anotherfield

所需的输出

a very long string..........     112232432      anotherfield
a smaller string                 123124343      anotherfield

推荐答案

printf很棒,但人们对此却忘却了.

printf is great, but people forget about it.

$ for num in 1 10 100 1000 10000 100000 1000000; do printf "%10s %s\n" $num "foobar"; done
         1 foobar
        10 foobar
       100 foobar
      1000 foobar
     10000 foobar
    100000 foobar
   1000000 foobar

$ for((i=0;i<array_size;i++));
do
    printf "%10s %10d %10s" stringarray[$i] numberarray[$i] anotherfieldarray[%i]
done

注意,我将%10s用于字符串. %s是重要的部分.它告诉它使用字符串.中间的10表示要多少列. %d用于数字(数字).

Notice I used %10s for strings. %s is the important part. It tells it to use a string. The 10 in the middle says how many columns it is to be. %d is for numerics (digits).

man 1 printf了解更多信息.

这篇关于如何在Bash中对齐表的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆