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|
?
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
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|