Bash: using printf to display fixed-width padded string

One way to implement character padding in Bash is to use printf and substring extraction.  This can be especially useful in reports or menu display.

Given a $padding variable that contains the maximum length of characters, you can subtract out the length of a display string like below.

# length of maximum padding
padding="......................................"

printf "==== TABLE OF CONTENTS ===========================\n"

# print first line
title="1) Chapter one - the intro"
printf "%s%s %s\n" "$title" "${padding:${#title}}" "Page 1"

# print second line
title="2) Chapter two - summary"
printf "%s%s %s\n" "$title" "${padding:${#title}}" "Page 4"

Which would look like this on screen

==== TABLE OF CONTENTS ===========================
1) Chapter one - the intro............ Page 1
2) Chapter two - summary.............. Page 4

Here is a full example, test_string_padding.sh

REFERENCES

stackoverflow Fritz G Mehner solution with bash substring extraction

stackoverflow J Jorgenson, another solution for printf padding

cyberciti.biz, bash substring extraction