# echo "thislinehas%allovertheplace%%asdf%%" | awk '{print $0}'

Really quick… the above and below commmand simply tells awk to print the inputed line, so that the output should look as if it was only the echo command that was run (without the awk). if there were multiple lines it should print them all.

However the below case simply shows to be problematic when the given variable in this case $0 has a %. Note that the variable could of been anything it could of been something like x=”234%432″ and then we were asked to printf x; it would fail simply because the x has a % sign.

SIDE NOTE: print automatically ends the line with a newline, but printf doesnt so I had to add in (concat in) the “\n” so that in reality the passed in string to printf looks like this “thislinehas%allovertheplace%%asdf%%\n”

# echo "thislinehas%allovertheplace%%asdf%%" | awk '{printf $0 "\n"}'
awk: run time error: not enough arguments passed to printf("thislinehas%allovertheplace%%asdf%%")

Why does it fail when there is a %? because it expects the % to be lead up with formatting arguments. After all printf is all about the percent sign formatting – just look at this printf guide from the c programming language http://www.cplusplus.com/reference/cstdio/printf/ or this one which belong more (from awk) https://www.gnu.org/software/gawk/manual/html_node/Printf-Examples.html

The fix is adding in gsub(“%”,”%%”,$0), which simply replaces each % with a %% in the $0

So a line such as “thislinehas%allovertheplace%%asdf%%” would actually look like this when its passed to printf: “thislinehas%%allovertheplace%%%%asdf%%%%”. So each %% turns into an %.

# echo "thislinehas%allovertheplace%%asdf%%" | awk '{gsub("%","%%",$0);printf $0 "\n"}'


SIDE NOTE: if you were wondering, yes the printf actually got “thislinehas%%allovertheplace%%%%asdf%%%%\n” with that extra “\n” at the end for the newline

For kicks if we passed it thru regular print, it would look like this

# echo "thislinehas%allovertheplace%%asdf%%" | awk '{gsub("%","%%",$0);print $0}'


NOTE: if your variable passed into printf has other chars like \, they would need to be treated correctly as well (probably in a different manner since \ is a global escape character that applies not only in awk but in bash as well).

Leave a Reply

Your email address will not be published. Required fields are marked *