How to change the decimal separator with awk/sed?

后端 未结 8 1256
萌比男神i
萌比男神i 2020-12-31 10:40

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

8条回答
  •  时光说笑
    2020-12-31 11:33

    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)

提交回复
热议问题