Text alignment center - shell script

2019-03-28 00:09发布

问题:

I'm creating a simple console based script using shell script.It will be run on my bash shell Its a simple menu based driven display some set of options.

Now I want to do center align the text depending on the screen size. How do I align the text at center of the screen?Please assis me

回答1:

Finally I found the solution:)

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


回答2:

On BSD-based systems, including MacOS, the fmt utility has a -c flag to center text.

echo $text | fmt -c -w $COLUMNS

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



回答3:

Simple Perl solution:

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


标签: shell ubuntu