your daily cup of tea™

powered by

Centering ANSI images on a terminal

Nothing screams last decade like CSS centering. Nowadays it’s all about the terminal. Say you have this nice snorlax on a text file. It all looks nice, except it’s not centered.

It’s full of ANSI escape codes, so fmt won’t do it

We could clean it up

Get the length of the longest line

Get the width of the terminal, subtract the length and divide it by two

Finally use that magic number and pad your snorlax

Ah yes, a nice oneliner

you know.. let’s make it nice and readable

function center {
  local f p s
  f=$(mktemp);p=${1:-$(tput cols)};s="s,\x1B\[[0-9;]*[a-zA-Z],,g";cat>$f
  s=$(cat $f|sed $s|while IFS= read -r l;do echo ${#l};done|sort -n|tail -1)
  s=$(((p-s)/2));s=$(printf "%${s}s" " ");cat $f|sed -e 's/^/'"$s"'/';rm $f
}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.