Text alignment center - shell script

2019-03-27 23:52发布

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

标签: shell ubuntu
3条回答
Fickle 薄情
2楼-- · 2019-03-28 00:08

Finally I found the solution:)

COLUMNS=$(tput cols) 
title="Hello world!" 
printf "%*s\n" $(((${#title}+$COLUMNS)/2)) "$title"
查看更多
一纸荒年 Trace。
3楼-- · 2019-03-28 00:16

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.

查看更多
乱世女痞
4楼-- · 2019-03-28 00:21

Simple Perl solution:

perl -pe '$sp = " " x (($ENV{COLUMNS} - length) / 2); s/^/$sp/'
查看更多
登录 后发表回答