Centering a string

Center a string using awk

awk = everyone’s favorite - right?

People who know me also know that I prefer simple universally available tools to get a job done. Awk is probably one of my favorites because it does pretty much anything I need for quick and simple jobs. It is far more powerful than most people realize including associative arrays and it will do anything grep and sed
can do.

Recently I had the need to center a string of text. This is a easy problem that pretty much any freshman programmer can accomplish in a heartbeat but I decided to do it with awk. This sample gives you a chance to explore rudimentary features of awk.

Assumptions:

  • STRING = “my string for centering”
  • LLEN = 65 # This is the line length
echo $STRING | awk -vllen=$LLEN '
  BEGIN{for(i=1;i<=llen;i++){printf i%10};printf "\n"}
  {
  startpos = (llen - length)/2;
  for(i=1;i<=startpos;i++)
  {
    printf " "
  }
  print $0
  }' 

The BEGIN section is just to provide a rule line

“length” is the length of the line fed into awk ($0 variable). “startpos” is the start position for the string - the for
loop just prints a space until startpos is reached (printf
is used to avoid a line break).

Not perfect but it works for me.

-g-

Geoff McNamara

"Do not meddle in the affairs of wizards, for they are subtle and quick to anger.” J.R.R Tolkien

Elizabeth City, NC https://www.companionway.net



Credits: