Awk: Centering Text Using Printf


Recommended Posts

Hello everyone, I have an assignment which requires me to center text using Printf in Awk, I tried googling for a bit but none seem to do what I need, could someone please enlighten me? Thank you!

Link to comment
https://www.neowin.net/forum/topic/499928-awk-centering-text-using-printf/
Share on other sites

awk '{ printf("%*s\n", ('${COLUMNS}' + length($1))/2, $1); }'

Where $1 is, of course, the stuff you want to center. This should work in bash, maybe in zsh... don't know about other shells.

Brief overview:

printf with a * takes the width as a parameter before the string

${COLUMNS} is the number of columns in the terminal according to the shell -- you can see that it is not part of the actual awk expression, but rather evaluated at the shell level (this is the reason it might only work in bash and zsh)

length($1) is the size of the variable you want to center

You then divide the sum of these two parts by 2 to get the text off-center by +<N> (awk right-justifies text by default)

The second parameter to printf is the actual text you want to center

Hope this helped... ;)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.