Left align with printf in bash with unknown width

861 Views Asked by At

I am trying to left align with printf in bash with unknown width.

How do I do so?

So sort of like this, but this does not work

max=<enter random number>
printf "%-${max}s|", "Instance"

The point of this is the instance below will be an unknown length that can is dynamic in length.

Example Input

max=10

Example Output

Instance  |

Example Input2

max=12

Example Output2

Instance    |
2

There are 2 best solutions below

2
On BEST ANSWER

You can use an * for the length:

for ((max=8;max<15;max++)); do
    printf "%-*s|\n" ${max} "Instance"
done

Result:

Instance|
Instance |
Instance  |
Instance   |
Instance    |
Instance     |
Instance      |
0
On

I suppose you're trying to print a table. I think you won't be able to do this with printf alone. This would basically require your line outputting command to predict the future output.

If you can tolerate post-processing though, you can simply do it using the column command. Just pick a character you'd like to replace with padding, and do as in the following example (I've picked the backslash \):

printf "%s\\|\n" "Instance" "Linstance" "Mintinginstance" | column -ts'\'

Output:

Instance         |
Linstance        |
Mintinginstance  |