用逗号替换句号

用逗号替换句号

对于下面的值,我必须替换第二个和第四个“。”在下面的文件中通过“,”

输入

1.351364711.103.7319660.2010-01-01 00:00:00
1.345529841.103.7372875.2010-01-01 00:00:49
1.342955629.103.7455272.2010-01-01 00:01:42
1.339694956.103.7520503.2010-01-01 00:02:28

期望的中间输出

    1.351364711,103.7319660,2010-01-01 00:00:00
    1.345529841,103.7372875,2010-01-01 00:00:49
    1.342955629,103.7455272,2010-01-01 00:01:42
    1.339694956,103.7520503,2010-01-01 00:02:28

我知道awk gsub(/./,",")这会用逗号替换所有内容。但我只需要用 "," 分隔列。之后我还想首先切换第三列。

期望的最终输出

2010-01-01 00:00:00,1.351364711,103.7319660
2010-01-01 00:00:49,1.345529841,103.7372875
2010-01-01 00:01:42,1.342955629,103.7455272
2010-01-01 00:02:28,1.339694956,103.7520503

答案1

bash-4.1$ cat file
1.351364711.103.7319660.2010-01-01 00:00:00
1.345529841.103.7372875.2010-01-01 00:00:49
1.342955629.103.7455272.2010-01-01 00:01:42
1.339694956.103.7520503.2010-01-01 00:02:28

bash-4.1$ awk -F. '{print $NF,$1"."$2,$3"."$4}' OFS=, file
2010-01-01 00:00:00,1.351364711,103.7319660
2010-01-01 00:00:49,1.345529841,103.7372875
2010-01-01 00:01:42,1.342955629,103.7455272
2010-01-01 00:02:28,1.339694956,103.7520503

答案2

使用sed

$ sed 's/\./,/4; s/\./,/2' file
1.351364711,103.7319660,2010-01-01 00:00:00
1.345529841,103.7372875,2010-01-01 00:00:49
1.342955629,103.7455272,2010-01-01 00:01:42
1.339694956,103.7520503,2010-01-01 00:02:28

首先用逗号替换第四个点,然后是第二个点。

我们也可以按照相反的顺序进行替换,但是由于替换第二个点会从行中删除一个点,因此最初的第四个点变成了第三个点:

$ sed 's/\./,/2; s/\./,/3' file
1.351364711,103.7319660,2010-01-01 00:00:00
1.345529841,103.7372875,2010-01-01 00:00:49
1.342955629,103.7455272,2010-01-01 00:01:42
1.339694956,103.7520503,2010-01-01 00:02:28

s/.../.../n语法(其中n是数字)替换一行中第 n: 个匹配的出现。

将最后一列移到前面可以通过以下方式完成

s/^\(.*\),\([^,]*\)/\2,\1/

即,匹配从行开头到逗号的内容,然后是逗号,然后是不再包含逗号的内容。

所以完整的命令可能是

$ sed 's/\./,/4; s/\./,/2; s/^\(.*\),\([^,]*\)/\2,\1/' file
2010-01-01 00:00:00,1.351364711,103.7319660
2010-01-01 00:00:49,1.345529841,103.7372875
2010-01-01 00:01:42,1.342955629,103.7455272
2010-01-01 00:02:28,1.339694956,103.7520503

相关内容