How to change the decimal separator with awk/sed?

后端 未结 8 1257
萌比男神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:16

    if you have bash/ksh etc

    var=XXX.XXX
    echo ${var/./,}
    
    0 讨论(0)
  • 2020-12-31 11:18

    Since the question is also tagged awk:

    awk 'gsub(/\./,",")||1'
    
    0 讨论(0)
  • 2020-12-31 11:25

    To substitute only the decimal commas in this line:

    Total,"14333,374","1243750945,5","100,00%","100,00%","100,00%",1 639 600,"100,00%"
    

    I used back-references (and MacOSX, so I need the -E option):

    echo 'Total,"14333,374","1243750945,5","100,00%","100,00%","100,00%",1 639 600,"100,00%"'  | sed -E 's/("[0-9]+),([0-9]+%?")/\1\.\2/g' 
    

    resulting in

    Total,"14333.374","1243750945.5","100.00%","100.00%","100.00%",1 639 600,"100.00%"
    

    The sed command says: "Find every string of the form 'double quotes digit_1,digit_2, followed by one or zero %, double quotes' and replace it by first_match.second_match."

    0 讨论(0)
  • 2020-12-31 11:28

    I think

    s/\./,/g
    

    should serve what u want... unless u want something more special...

    0 讨论(0)
  • 2020-12-31 11:31

    How rigorous do you want to be? You could change all . characters, as others have suggested, but that will allow a lot of false positives if you have more than just numbers. A bit stricter would be to require that there are digits on both sides of the point:

    $ 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
    

    That does allow changes in a couple of odd cases, namely 255.255.255.0 and a1.1a, but handles "normal" numbers cleanly.

    0 讨论(0)
  • 2020-12-31 11:31

    You could do this:

    echo "XXX.XX" | sed s/\./,/g
    
    0 讨论(0)
提交回复
热议问题