Ryan Harlich
Ryan Harlich

Reputation: 177

Left align with printf in bash with unknown width

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    |

Upvotes: 2

Views: 958

Answers (2)

Walter A
Walter A

Reputation: 19982

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      |

Upvotes: 3

Ruslan
Ruslan

Reputation: 19120

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  |

Upvotes: 3

Related Questions