替换CSV文件第一行中的第n个字段

时间:2017-11-20 07:27:08

标签: shell

我有一个包含数据的CSV文件test.csv FHEAD,0000000001,STKU,20150927000000,201509270000000000,1153,,0000000801,W FDETL,1,2,3 FDETL,9,7,4 FTAIL,2,3,4

我想将6th行开头FHEAD替换为文件test.csv中的某些派生值,结果文件内容将如下所示 cat test.csv FHEAD,0000000001,STKU,20150927000000,201509270000000000,0000,,0000000801,W FDETL,1,2,3 FDETL,9,7,4 FTAIL,2,3,4

我如何在shell脚本中执行此操作。

2 个答案:

答案 0 :(得分:0)

这是使用awk的人:

$ awk 'BEGIN{ FS=OFS="," }           # set delimiters
/^FHEAD/ {                           # if row starts with FHEAD
    $6="some derived value"          # replace 6th filed to some derived value
} 
1' file                              # output
FHEAD,0000000001,STKU,20150927000000,201509270000000000,some derived value,,0000000801,W

答案 1 :(得分:0)

您可以使用sed

sed '/^FHEAD/s/\(,[^,]*\)/,newvalue/5' infile