I am trying to display a number with commas
printf "%d\n" 323232
printf "%d\n" 1234567
I want the output to be:
323,232
1,234,567
I tried to change %d to other formats and could find the solution.
any idea?
I am trying to display a number with commas
printf "%d\n" 323232
printf "%d\n" 1234567
I want the output to be:
323,232
1,234,567
I tried to change %d to other formats and could find the solution.
any idea?
Search the Web for a script called nicenumber.sh
Aternatively use this sed one liner which handles up to 3 decimal places correctly
$ echo 1234567 | sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'
1,234,567
$ echo 1234567.123 | sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'
1,234,567.123
works good, thanks
Do yo have a solution within awk ?
well, you can do it like this with sed:
# echo 12345678 | sed -e :x -e 's/\([0-9][0-9]*\)\([0-9][0-9][0-9]\)/\1,\2/' -e 'tx'
12,345,678
I found almost working solution
echo 1 12 123 1234 12345 123456 1234567 | awk --re-interval '{print gensub(/([[:digit:]])([[:digit:]]{3})/,"\\1,\\2","g")}'
1 12 123 1,234 1,2345 1,23456 1,234567
any idea how to fix it ?
From the gawk manual
A single quote or apostrohe character is a POSIX extension to ISO C. It indicates that the integer part of a floating point value, or the entire part of an integer decimal value, should have a thousands-separator character in it. This only works in locales that support such characters.
$ cat thousands.awk
BEGIN { printf "%'d\n", 1234567 }
$ LC_ALL=C gawk -f thousands.awk
1234567
$ LC_ALL=en_US.UTF-8 gawk -f thousands.awk
1,234,567
this is not working under linux
Hi.
The solution posted by fpmurphy worked in the Linux I use:
#!/bin/bash -
# @(#) s1 Demonstrate feature.
echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version =o $(_eat $0 $1) awk
FILE=thousands.awk
cat >$FILE <<'EOF'
BEGIN { printf "%'d\n", 1234567 }
EOF
echo
echo " awk script:"
cat $FILE
echo
echo " Results with LC_ALL=C:"
LC_ALL=C gawk -f $FILE
echo
echo " Results with LC_ALL=en_US.UTF-8:"
LC_ALL=en_US.UTF-8 gawk -f $FILE
exit 0
Producing:
% ./s1
(Versions displayed with local utility "version")
Linux 2.6.11-x1
GNU bash 2.05b.0
GNU Awk 3.1.4
awk script:
BEGIN { printf "%'d\n", 1234567 }
Results with LC_ALL=C:
1234567
Results with LC_ALL=en_US.UTF-8:
1,234,567
Best wishes ... cheers, drl