Operating System - HP-UX
1834650 Members
2265 Online
110069 Solutions
New Discussion

Re: Center text on the screen

 
SOLVED
Go to solution
Robert Fisher_1
Frequent Advisor

Center text on the screen

Hi,

Does anyone have an example of an easy way to center
text messages on a terminal? I would like to easily center menu titles without having to count spaces.

Thanks in advance for any ideas,
Bob
5 REPLIES 5
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Center text on the screen

Hi Bob:

I ain't got one but it shouldn't be too difficult to whup one up.

#!/usr/bin/sh


centerit()
{
if [[ ${#} -lt 1 ]]
then
return 255
fi
XS=${1}
shift
while [[ ${#} -ge 1 ]]
do
XS="${XS} ${1}"
shift
done
XPOS=$((($(tput cols) - ${#XS}) / 2))
XI=0
while [[ ${XI} -lt ${XPOS} ]]
do
echo " \c"
XI=$((${XI} + 1))
done
echo "${XS}"
return 0
}

#example
centerit "This is a test"
# or
centerit This is a test


Note that this uses tput cols to get the screen width so it should work on any terminal.
If I didn't miss any typo's then this guy should also work if you quote the args (suggested) or not.
If it ain't broke, I can fix that.
H.Merijn Brand (procura
Honored Contributor

Re: Center text on the screen

# perl -e'$msg="@ARGV";printf"%*s%s\n",(($ENV{COLUMNS}||80)-length$msg)/2,"",$msg' Your message

Enjoy, have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
A. Clay Stephenson
Acclaimed Contributor

Re: Center text on the screen

One other thing Bob, since you mentioned menu titles, you might want to add something like tput smso's tput rmso's around your titles to make them stand out. (smso/rmso start standout mode; remove standout mode).
If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: Center text on the screen

Hi Bob:

Here's a crude example:

#!/usr/bin/sh
MSG="This message is centered!"
MSZ=${#MSG}
COL=`echo "(80-${MSZ})/2"|bc`
clear
tput cup 12 ${COL}
echo ${MSG}
tput cup 23 0
exit 0

Regards!

...JRF...
Robert Fisher_1
Frequent Advisor

Re: Center text on the screen

Thanks guys. JRF, I should have stated that I only needed to center the text horizontally. Procura, the perl was neat! I am going to have to learn it. A. Clay, I followed your advice and made a second function that does a tput smso and a tput rmso.

Thanks,
Bob