Text alignment center - shell script

I am creating a simple console script using a shell script. It will be launched on my bash shell. Its simple managed menu controls the display of a certain set of parameters.

Now I want the center to align the text depending on the size of the screen. How to align the text in the center of the screen? Please help me

+5
source share
3 answers

Finally, I found a solution :)

COLUMNS=$(tput cols) 
title="Hello world!" 
printf "%*s\n" $(((${#title}+$COLUMNS)/2)) "$title"
+11
source

On BSD-based systems, including MacOS, the utility fmthas a flag -cfor the center of the text.

echo $text | fmt -c -w $COLUMNS

Unfortunately, GNU fmthas an incompatible -c flag and has no alternative for centering.

+5
source

Perl:

perl -pe '$sp = " " x (($ENV{COLUMNS} - length) / 2); s/^/$sp/'
0

All Articles