Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

The sed FAQ
Prev Home Next

4.14. How do I commify a string of numbers?

Use the simplest script necessary to accomplish your task. As variations of the line increase, the sed script must become more complex to handle additional conditions. Whole numbers are simplest, followed by decimal formats, followed by embedded words.

Case 1: simple strings of whole numbers separated by spaces or commas, with an optional negative sign. To convert this:

       4381, -1222333, and 70000: - 44555666 1234567890 words
       56890  -234567, and 89222  -999777  345888777666 chars

to this:

       4,381, -1,222,333, and 70,000: - 44,555,666 1,234,567,890 words
       56,890  -234,567, and 89,222  -999,777  345,888,777,666 chars

use one of these one-liners:

     sed ':a;s/\B[0-9]\{3\}\>/,&/;ta'                      # GNU sed
     sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'  # other seds

Case 2: strings of numbers which may have an embedded decimal point, separated by spaces or commas, with an optional negative sign. To change this:

       4381,  -6555.1212 and 70000,  7.18281828  44906982.071902
       56890   -2345.7778 and 8.0000:  -49000000 -1234567.89012

to this:

       4,381,  -6,555.1212 and 70,000,  7.18281828  44,906,982.071902
       56,890   -2,345.7778 and 8.0000:  -49,000,000 -1,234,567.89012

use the following command for GNU sed:

     sed ':a;s/\(^\|[^0-9.]\)\([0-9]\+\)\([0-9]\{3\}\)/\1\2,\3/g;ta'

and for other versions of sed:

     sed -f case2.sed files

     # case2.sed
     s/^/ /;                 # add space to start of line
     :a
     s/\( [-0-9]\{1,\}\)\([0-9]\{3\}\)/\1,\2/g
     ta
     s/ //;                  # remove space from start of line
     #---end of script---
The sed FAQ
Prev Home Next

 
 
   Reprinted courtesy of Eric Pement. Also available at http://sed.sourceforge.net/sedfaq.html Design by Interspire