SUMMARY: Formatting Numbers to be Comma Separated

From: Sumair Mahmood <>
Date: Thu Dec 05 2002 - 16:35:46 EST

Any suggestions on how I can format numbers so that they come
out comma separated?

INPUT:	echo "123456789" | <command>
OUTPUT:	123,456,789

My research into awk/nawk [and print/printf] didn't prove very
successful.  It seems only to do floating point, e-notation, etc.
I suppose I could write a script to do this, but I'm hoping there
is a Solaris utility / option I'm simply over looking.


1.  John Leadeham provided the sed solution I needed:

   From Eric Pement's Handy One-Liners for Sed document at

   # add commas to numeric strings, changing "1234567" to
   # "1,234,567"
   gsed ':a;s/\B[0-9]\{3\}\>/,&/;ta'                     # GNU sed
   sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'  # other seds

   # add commas to numbers with decimal points and minus
   # signs (GNU sed)
   gsed ':a;s/\(   \|[   0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g;ta'

2. Darren Dunham, Dave Mitchell, and Andy Bach
   demonstrated the same in Perl:

   This is a frequently asked question of perl, so if you have
   that installed you can type
   	% perldoc -q "commas added"
   and see the entry for doing this as a perl script.

   $ echo "1234567890" | perl -pe '1 while s/(.*)(\d)(\d\d\d)/$1$2,$3/'

3. And Tim's awk script is something I aspire to be able to emulate
    one day!

   Here is one example, it works with any number of digits, as far
   as is reasonable.  It  does NOT zero fill:

        while (len > 0) #Going to pick off digits one at a time
#          printf("Current digit is %d\n",digit)
           if (place > 3)
             {place = 1
              {outval=digit outval
#       printf("pretty number is %s\n",outval)
printf("pretty number is %s\n",outval)

 Sumair Mahmood
 Sr. Unix Systems Engineer
 QLogic Corporation

sunmanagers mailing list
Received on Thu Dec 5 16:39:04 2002

This archive was generated by hypermail 2.1.8 : Thu Mar 03 2016 - 06:42:59 EST