如何替换csv的所有列中的特定值?

时间:2017-07-20 14:25:54

标签: linux awk

我有这些数据:

111,24,1,\N,\N,[],aa
222,25,2,\N,\N,[],bb
333,26,3,\N,\N,[],\N

我想使用\N替换第4和第5列中的所有awk

我写了这个,但不确定我是在正确的方式:

awk -F "," '{print $1 "," $2 "," $3 "," $4/ "," $5/ "," $6 "," $7}'

此解决方案不灵活。如果我有100列怎么办?

更新

预期产出:

111,24,1,4.3,2.1,[],aa
222,25,2,4.3,2.1,[],bb
333,26,3,4.3,2.1,[],\N

2 个答案:

答案 0 :(得分:4)

我写道:

awk '
    BEGIN {FS = OFS = ","}
    $4 == "\\N" {$4 = 4.3}
    $5 == "\\N" {$5 = 2.1}
    {print}
' file

或者,如果你的真实案例更复杂,那就像

awk '
    BEGIN {
        FS = OFS = ","
        repl[4] = 4.3
        repl[5] = 2.1
        repl[7] = "hello"
    }
    {for (i in repl) if ($i == "\\N") $i = repl[i]}
    {print}
' file

答案 1 :(得分:0)

awk -F, '{$4=4.3;$5=2.1}1' OFS=, file

111,24,1,4.3,2.1,[],aa
222,25,2,4.3,2.1,[],bb
333,26,3,4.3,2.1,[],\N

替换$ 4和$ 5列中的值。