Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printf left align and right align to obtain a fixed length string without truncation by varying space separators

I would like to obtain the following output from Bash printf using three variables (code, parameter, value):

[OK] Percentage:                 100%
[OK] Ping time:                  31ms
[OK] Memory usage:                7MB
[KO] Main Drive Temperature:    104°C
[OK] Uptime:               4d 22h 32m

Space between parameter 1 and 2 is one space since 1 is always four characters long, while space between 2 and 3 varies to make the total length equal to 37 (arbitrary number). There is no truncation of either parameters or values, if their sum exceeds 37 I just specify a bigger number as the total string length, also for all the other lines.

This gets the job done most of the time, but it’s not perfect:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

printf '%s %-20s %11s\n' "$1" "$2" "$3"

>Solution :

You have all the strings with length. Take a piece of paper and draw it. For example:

[OK] |--------------------------------|  the whole space
                                 |----|  trailing part
     |---------------------------|       initial part = the whole space - trailing part

 width=40
 printf "%s %-*s%s\n" "[OK]" "$((width - ${#3}))" "$2" "$3"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading