Trying to center my output text

Im stumped on how to center the output of my echo command. I also would like to center my calender too, but is the command to center the same for echo and cal?

cal is written in C and the output witdh is always known ahead of time.

This example depends on the COLUMNS environment variable, which can be changed by some things after you login -- to no longer match your tty.

center()
{
     
     value="$1" 
     if [[ $value -lt $COLUMNS ]] ; then
       width=$(( (  $COLUMNS - ${#value} ) / 2 ))
       printf "%${width}s\n"  "$1"
     else
        echo "$1"
     fi
}

#usage
center "print me at the center"

assuming the your width is 79:

cal | sed  -e :a -e 's/^.\{1,77\}$/ & /;ta' 

Courtesy of sed1liners

1 Like

both worked according to plan, thanks gentlemen