Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the decimal separator with awk/sed?

Tags:

sed

awk

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

like image 232
racix Avatar asked Aug 09 '10 10:08

racix


1 Answers

If you want to replace the decimal separator for cosmetic purposes

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

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

Of course if you deal with input mixing numbers and strings, you will need a more robust approach, like the one proposed by Michael J. Barber or even more.

If you want to replace the decimal separator for computation purposes

By default gawk (GNU awk, i.e. the awk of most GNU/Linux distributions) uses the dot as 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 using 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 redefine 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)

like image 126
Skippy le Grand Gourou Avatar answered Oct 05 '22 12:10

Skippy le Grand Gourou