Shell编程 - 如何printf像表一样对齐我的输出?

时间:2012-07-18 17:46:47

标签: linux shell sh

如何像表格一样打印输出?

Title                                             Author
BaokyBook                                              Baoky2
Use basename commandUse basename command ..             Baoky

我的部分代码就像这样

titlelength=${#title};

首先我获得标题长度,然后我就像这样打印

titlespace=`expr 60 - titlelength`;
printf "%s %${titlespace}s\n" "$title" "$author"

但是对齐不正确,我如何才能使其正确对齐

回答以下答案:

进行更改后

我左边的所有左边都对齐了。它似乎不起作用。

1 个答案:

答案 0 :(得分:4)

最简单的方法是在固定宽度上打印标题:

printf "%30s %s\n" "$title" "$author"

如果要确定最大宽度,则需要在执行任何输出之前读取所有数据。或者您可以简单地将输出传输到column -t。或者,将标题截断为所选宽度(这种截断字符串的技术是一种基础):

 printf "%30s %s\n" "${title:0:30}" "$author"