1

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"
tripleee
  • 175,061
  • 34
  • 275
  • 318
Polizi8
  • 155
  • 1
  • 9
  • Note that if you want the longest line to determine the width, you have to read through the entire input first, to get this number. You can do it with `wc -L` (not POSIX) or awk. You specified `printf`, but also worth mentioning: `column -ts $'\t' -R 3 my-file` if you have tab delimited input for example (and `column(1)`). `-R 3` aligns column three to the right. – dan Feb 06 '22 at 11:39

1 Answers1

2

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"
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 1
    This works, thanks! Just to specify, the 40 referst to the whole space AFTER the first parameter. To get the total lenght you have to sum the lenght of the first string and a space (4+1 in my case) – Polizi8 Feb 06 '22 at 11:20