awk can print numbers with a thousands separator character:
$ awk "BEGIN {printf \"%'d\", 1000}"
1,000
However the fact that it requires a single quote means that you have to escape
every "
and $
in the entire script:
$ echo 1000 2000 | awk "{printf \"%'d\", \$2}"
2,000
This is easy enough here but could be troublesome with large examples. I thought of doing something like this:
$ echo 1000 2000 | awk '{printf z, $2}' z="%'d"
2,000
but even this is not great for advanced examples:
$ echo 1000 2000 | awk '{printf "hello " z " world " z, $1, $2}' z="%'d"
hello 1,000 world 2,000
I tried messing with OFMT
and CONVFMT
, but they seem to have no effect:
$ echo 1000 2000 | awk '{print $2}' OFMT="%'d" CONVFMT="%'d"
2000
Can those variables be used in the way I am trying to use them, or is another method available that better deals with the quoting issue?
To embed a single quote char in a single-quote-delimited command-line script just use the octal escape sequence \047
wherever you want the quote:
$ awk 'BEGIN {printf "%\047d\n", 1000}'
1,000
Bonus Points: Do not use the equivalent hex escape sequence \x27
:
$ awk 'BEGIN{print "\047foo!\047"}'
'foo!'
$ awk 'BEGIN{print "\x27foo!\x27"}'
oo!'