Is it possible to set the padding character for the printf function of gawk?

By default, gawk pads the content to the specified length with space character:

root@u2004:~# awk 'BEGIN{printf("|%+5s|n", "abc")}'
|  abc|
root@u2004:~#

Is it possible to specify a custom padding character? For example, how can I get |__abc|?

Asked By: Fajela Tajkiya

||

No, that will not work. gawk uses the printf function which does not support other padding characters according to this reference:

https://bytes.com/topic/c/answers/219695-printf-padding-alternate-character

Answered By: Ned64

Not directly but using GNU awk for gensub and assuming you don’t have any other blanks in your string to be printed ("abc" in this case):

$ awk 'BEGIN{ print gensub(/ /,"_","g",sprintf("|%5s|","abc")) }'
|__abc|

or using any awk whether your string contains blanks or not:

$ awk 'BEGIN{ base=sprintf("%1000s",""); gsub(/ /,"_",base);
        str="abc"; printf "|%s%s|n", substr(base,1,5-length(str)), str }'
|__abc|

or:

$ awk '
    BEGIN{ printf "|%s|n", pad("abc",5,"_") }
    function pad(str,len,chr,    base) {
       base = sprintf("%*s",len-length(str),"")
       gsub(/ /,chr,base)
       return base str
    }
'
|__abc|
Answered By: Ed Morton
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.