bashprintftext-alignmentright-align

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:

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"