Padding characters in printf Padding characters in printf bash bash

Padding characters in printf


Pure Bash, no external utilities

This demonstration does full justification, but you can just omit subtracting the length of the second string if you want ragged-right lines.

pad=$(printf '%0.1s' "-"{1..60})padlength=40string2='bbbbbbb'for string1 in a aa aaaa aaaaaaaado     printf '%s' "$string1"     printf '%*.*s' 0 $((padlength - ${#string1} - ${#string2} )) "$pad"     printf '%s\n' "$string2"     string2=${string2:1}done

Unfortunately, in that technique, the length of the pad string has to be hardcoded to be longer than the longest one you think you'll need, but the padlength can be a variable as shown. However, you can replace the first line with these three to be able to use a variable for the length of the pad:

padlimit=60pad=$(printf '%*s' "$padlimit")pad=${pad// /-}

So the pad (padlimit and padlength) could be based on terminal width ($COLUMNS) or computed from the length of the longest data string.

Output:

a--------------------------------bbbbbbbaa--------------------------------bbbbbbaaaa-------------------------------bbbbbaaaaaaaa----------------------------bbbb

Without subtracting the length of the second string:

a---------------------------------------bbbbbbbaa--------------------------------------bbbbbbaaaa------------------------------------bbbbbaaaaaaaa--------------------------------bbbb

The first line could instead be the equivalent (similar to sprintf):

printf -v pad '%0.1s' "-"{1..60}

or similarly for the more dynamic technique:

printf -v pad '%*s' "$padlimit"

You can do the printing all on one line if you prefer:

printf '%s%*.*s%s\n' "$string1" 0 $((padlength - ${#string1} - ${#string2} )) "$pad" "$string2"


Pure Bash. Use the length of the value of 'PROC_NAME' as offset for the fixed string 'line':

line='----------------------------------------'PROC_NAME='abc'printf "%s %s [UP]\n" $PROC_NAME "${line:${#PROC_NAME}}"PROC_NAME='abcdef'printf "%s %s [UP]\n" $PROC_NAME "${line:${#PROC_NAME}}"

This gives

abc ------------------------------------- [UP]abcdef ---------------------------------- [UP]


Trivial (but working) solution:

echo -e "---------------------------- [UP]\r$PROC_NAME "