2

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    |
Ryan Harlich
  • 157
  • 1
  • 7

2 Answers2

3

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      |
Walter A
  • 19,067
  • 2
  • 23
  • 43
  • 1
    Thanks for the answer! It was not working before when I used it because I had " awk 'BEGIN { printf ... }' " wrapped around it. There was no need for the awk BEGIN for my purpose so problem solved. – Ryan Harlich Apr 01 '20 at 16:15
  • `awk` works too when you use `for ((max=8;max<15;max++)); do awk -v max=${max} 'BEGIN {printf("%-*s|\n", max, "Instance")}'; done`. – Walter A Apr 01 '20 at 18:20
2

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  |
Ruslan
  • 18,162
  • 8
  • 67
  • 136