Search code examples
shellformattingprintfstring-formatting

How to dynamically create formatting rules for printf?


I am trying to print several lines in multiple columns of 30 characters width:

#!/bin/bash
chars_width=15
full_string="a\\nb\\nc\\nd"
number_of_columns=$(( $(tput cols) / $chars_width ))

for ((i = 0; i < number_of_columns; i++)); do
    formatting_string="$formatting_string%%-"$chars_width"s "
done

echo "$full_string" | xargs -L $number_of_columns | \
    while read -r values
    do
        printf "$formatting_string\\n" $values
    done
exit

While running this I would expect it to output:

a              b              c              d

But it outputs:

%-15s %-15s %-15s %-15s

How to put my dynamically built formatting rules for printf to use?


Solution

  • Use single '%' chars in your format string. You've escaped them, so nothing gets substituted.