Shell Programing - How do printf align my output like a table?

How do I printf align my output as a table?

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

My partial code is like this

 titlelength=${#title}; 

First I get the length of the header, then I print it as

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

But the alignment is not correct, how can I make it work well aligned

In response to the answer below:

after making changes

all my left ones are aligned to the right. and it does not work.

+4
source share
1 answer

The easiest way would be to print the header at a fixed width:

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

If you want to determine the maximum width, you will need to read all the data before making any output. or you can just pass your output to column -t . Or, truncate the title to the selected width (this line-cutting technique is bashism):

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

All Articles