Lighthalzen Posted October 1, 2006 Share Posted October 1, 2006 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 More sharing options...
impl Posted October 2, 2006 Share Posted October 2, 2006 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... ;) Link to comment https://www.neowin.net/forum/topic/499928-awk-centering-text-using-printf/#findComment-587923282 Share on other sites More sharing options...
Lighthalzen Posted October 2, 2006 Author Share Posted October 2, 2006 Thanks, I will give it a go once I get home! :D Link to comment https://www.neowin.net/forum/topic/499928-awk-centering-text-using-printf/#findComment-587923377 Share on other sites More sharing options...
Recommended Posts