Pad a string with a character | Fill in empty space with repeating character in bash

If you want to pad a string so that the string is always the same length, but if a string that is smaller than the required length is used the excess space is filled with a defined character so that the string maintains the correct spacing.

For example you want
FF
to be
00000000FF
or
FFF
to be
0000000FFF

It is always ten long.

Here is a custom function to help you achieve this.

Example:

$char="0";
$pad_length=10;
$str_to_pad="FF";

pad_str $char $pad_length $str_to_pad;

Output:

00000000FF

The custom function:

function pad_str(){
pad=$(printf '%0.1s' $1{1..60})
padlength=$2;
string1=$3;

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

Note: This will only pad up to a length of 60 if you want to pad more then you will need to change this value ( {1..60} ) to a greater value, like {1...1000}

Source: http://stackoverflow.com/questions/4409399/padding-characters-in-printf

comments powered by Disqus