更改csv文件中的decimal的格式

时间:2016-11-23 12:38:22

标签: bash unix awk sed floating-point

我有一个具有以下格式的CSV文件:

ffsdfff llkkfk fdflmk,000,1254489632,-1256.56,,0
jlfgdgf gfgfkl kiefnf,000,2548562325,2141.6,,262.54
dfgjklf kklfgk llfsmf,000,8654344845,25.3,8654344845,-25.25
sdfsklf dfsdfg gfdggs,000,2256352124,20,2256352124,-19

我很难得到这个结果:

ffsdfff llkkfk fdflmk,000,1254489632,-,000000000001256560,          ,+,000000000000000000
jlfgdgf gfgfkl kiefnf,000,2548562325,+,000000000002141600,          ,+,000000000000262540
dfgjklf kklfgk llfsmf,000,8654344845,+,000000000000025300,8654344845,-,000000000000025250
sdfsklf dfsdfg gfdggs,000,2256352124,+,000000000000020000,2256352124,-,000000000000019000

我希望将符号(+/-)与十进制数字分开。然后将每个小数的实际长度更改为18.(数字的小数部分的最大长度为3)。

如果第四个字段为空,我必须为其添加10个空格。

1 个答案:

答案 0 :(得分:2)

你可以试试awk

awk '
    BEGIN{OFS=FS=","}
    function abs(v) {return v < 0 ? -v : v}
    {
        $8=abs($6*1000)
        $7=($6<0 ? "-" : "+")
        $6=$5
        $5=abs($4*1000)
        $4=($4<0 ? "-" : "+") 
        $8=sprintf("%018d", $8)
        $6=sprintf("%10s", $6)
        $5=sprintf("%018d", $5)
        print
    }' input.txt

你明白了,

ffsdfff llkkfk fdflmk,000,1254489632,-,000000000001256560,          ,+,000000000000000000
jlfgdgf gfgfkl kiefnf,000,2548562325,+,000000000002141600,          ,+,000000000000262540
dfgjklf kklfgk llfsmf,000,8654344845,+,000000000000025300,8654344845,-,000000000000025250
sdfsklf dfsdfg gfdggs,000,2256352124,+,000000000000020000,2256352124,-,000000000000019000