The Linux Page

Creating a message of a length equal to a string in your console

Transform a frame so the message fits.

If you are writing many scripts, once in a while, you may want to print out a message surrounded by a box. But how do you create a box of the right width?

Say for example, that you want to surround your message with + characters like so:

+++++++++++++++++++
+ My Message Here +
+++++++++++++++++++

The message itself would be coming from a variable. Maybe there is a filename into it so the width can vary widely.

Say the line in the middle is written like so:

echo "+ ${MESSAGE} +"

Then you can create the string of just + characters with the following command:

DELIMITER="++`echo ${MESSAGE} | sed -e 's/./+/g'`++"

And now you can generate the box simply by doing this:

echo ${DELIMITER}
echo "+ ${MESSAGE} +"
echo ${DELIMITER}

Very simple and note that we never actually calculate the length of the message. We just use that as input in a tool which replaces all the characters (.) with a plus (+) character.