How to change number format (different decimal separator) from XXXXXX.XXX
to XXXXXX,XXX
using sed
or awk
?
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.
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)
Wouldn't this be more accurate as the OP whas talking about numbers.. to make sure it is a leading number before the dot. The document could hold other dots that the OP don't want to substitute.
sed '/[0-9]\./s/\./,/g'