How to change decimal separator to awk / sed?

How to change number format (different decimal separator) from XXXXXX.XXX to XXXXXX,XXX using sed or awk ?

+5
source share
7 answers

Wouldn't that be more accurate than the OP, which talks about numbers. To make sure this number is ahead of the point. The document may contain other points that the OP does not want to replace.

 sed '/[0-9]\./s/\./,/g' 
+5
source

How strict are you to want to be? You could change all the characters . as others suggested, but it will allow a lot of false positives if you have more than just numbers. It would be a bit stricter to require numbers on both sides of the dot:

 $ echo 123.324 2314.234 adfdasf.324 1234123.daf 255.255.255.0 adsf.asdf a1.1a | > sed 's/\([[:digit:]]\)\.\([[:digit:]]\)/\1,\2/g' 123,324 2314,234 adfdasf.324 1234123.daf 255,255,255,0 adsf.asdf a1,1a 

This allows you to change a few odd cases, namely 255.255.255.0 and a1.1a , but it processes the "normal" numbers cleanly.

+4
source

You can do it:

 echo "XXX.XX" | sed s/\./,/g 
+2
source

if you have bash / ksh etc

 var=XXX.XXX echo ${var/./,} 
+1
source

If you want to replace the decimal separator with cosmetic purposes

In most cases, tr is probably the easiest way to replace characters:

 $ echo "0.3"|tr '.' ',' 0,3 

Of course, if you are doing introductory mixes and strings, you will need a more robust approach, such as that suggested by Michael J. Barber or even more.

If you want to replace the decimal separator for calculation purposes

By default, gawk (GNU awk , i.e. awk most GNU / Linux distributions) uses the period as a decimal separator:

 $ echo $LC_NUMERIC fr_FR.UTF-8 $ echo "0.1 0.2"|awk '{print $1+$2}' 0.3 $ echo "0,1 0,2"|awk '{print $1+$2}' 0 

However, you can force it to use the decimal separator of the current locale with the --use-lc-numeric option:

 $ echo $LC_NUMERIC fr_FR.UTF-8 $ echo "0.1 0.2"|awk --use-lc-numeric '{print $1+$2}' 0 $ echo "0,1 0,2"|awk --use-lc-numeric '{print $1+$2}' 0,3 

If the input format is different from the current locale, you can, of course, override LC_NUMERIC temporarily:

 $ echo $LC_NUMERIC fr_FR.UTF-8 $ echo "0.1 0.2"|LC_NUMERIC=en_US.UTF-8 awk --use-lc-numeric '{print $1+$2}' 0 $ echo "0,1 0,2"|LC_NUMERIC=fr_FR.UTF-8 awk --use-lc-numeric '{print $1+$2}' 0,3 

( Credits and other links )

+1
source

I think,

 s/\./,/g 

should serve what you need ... if you want something more special ...

0
source

Since the question is also labeled awk :

 awk 'gsub(/\./,",")||1' 
0
source

All Articles