使用 sed 将逗号替换为点而不触及日期

and*_*and 3 sed

我需要将包含数字的字段的逗号 ( ,) 替换为点 ( )。.我的解决方案还替换了日期中的点,这是我不想要的。

我的出发点:

2020.01.02;2020-01-02;1.321;0.321;2.243;0.032

我想要的是:

2020.01.02;2020-01-02;1,321;0,321;2,243;0,032

这是我设法做的,但它也将日期中的点更改为,:

$ sed 's/\([0-9]*\)\.\([0-9]*\)/\1,\2/g' <file>
2020,01,02;2020-01-02;1,321;0,321;2,243;0,032
    |  |
    `--`--dont want to replace these
Run Code Online (Sandbox Code Playgroud)

我尝试;在表达式中使用来缩小范围,但这让我遇到了模式匹配的问题:

         |                      | |     |
$ sed 's/;\([0-9]*\)\.\([0-9]*\);/;\1,\2;/g' eg
2020.01.02;2020-01-02;1,321;0.321;2,243;0.032
                             |           |
                             ` not replaced
Run Code Online (Sandbox Code Playgroud)

只有其他的都.被替换。

或者

                             |      |
sed 's/\([0-9]*\)\.\([0-9]*\);/\1,\2;/g' eg
2020.01,02;2020-01-02;1,321;0,321;2,243;0.032
       |
       ` do not replace this

Run Code Online (Sandbox Code Playgroud)

任何提示或技巧将不胜感激!

Rav*_*h13 5

仅基于您显示的示例,如果您同意awk,您可以尝试以下操作。

awk '
BEGIN{
  FS=OFS=";"
}
{
  for(i=1;i<=NF;i++){
    if($i~/^[0-9]+\.[0-9]+$/){
      sub(/\./,",",$i)
    }
  }
}
1
'  Input_file
Run Code Online (Sandbox Code Playgroud)

或者,如果您正在查找一位数,然后.是 3 位数字,那么您可以尝试以下操作。

awk '
BEGIN{
  FS=OFS=";"
}
{
  for(i=1;i<=NF;i++){
    if($i~/^[0-9]\.[0-9]{3}$/){
      sub(/\./,",",$i)
    }
  }
}
1
' Input_file
Run Code Online (Sandbox Code Playgroud)