将值从一列复制到另一列

时间:2018-07-09 08:17:07

标签: linux shell

这是Linux系统中的一个csv文件。这是文件的一行。

:/var/opt/data# vi data_2018_07.csv

LGPAR,DATA,61543261,98747321900,gprs,464623201315531,NRI,1.45890,0.000000,0.0000,,2016-01-12 01:50:58,2016-01-12 15:50:58,0,11,0,0,0,0,25250,NO,NO,NO,1056.gz

类似地,该文件中有10,000行。我们要做的就是在NO,xxxx.gz之间的某个位置添加一个增量值(第24个值),例如:-

LGPAR,DATA,61543261,98747321900,gprs,464623201315531,NRI,1.45890,0.000000,0.0000,,2016-01-12 01:50:58,2016-01-12 15:50:58,0,11,0,0,0,0,25250,NO,NO,NO,1, 1056.gz
LGRDR,DATA,61543261,98747321900,gprs,464623201315531,NRI,1.45890,0.000000,0.0000,,2016-01-12 01:50:58,2016-01-12 15:50:58,0,11,0,0,0,0,25250,NO,NO,NO,2, 1057.gz

我们可以使用一个小的Shell脚本在整个文件的所有行中执行此操作吗? 注意:每行的行都是不同的。

3 个答案:

答案 0 :(得分:1)

您可以使用此awk

awk 'BEGIN{FS=OFS=","} {$24 = NR FS $24} 1' file.csv

LGPAR,DATA,61543261,98747321900,gprs,464623201315531,NRI,1.45890,0.000000,0.0000,,2016-01-12 01:50:58,2016-01-12 15:50:58,0,11,0,0,0,0,25250,NO,NO,NO,1,1056.gz

要将更改保存在同一文件中:

awk 'BEGIN{FS=OFS=","} {$24 = NR FS $24} 1' file.csv > tmp.csv && mv tmp.csv file.csv

答案 1 :(得分:0)

您可以使用 awk

awk -F"," '{ printf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n", $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $3, $24, $25); }'  yourcsv-file

给予:

LGPAR,DATA,61543261,98747321900,gprs,464623201315531,NRI,1.45890,0.000000,0.0000,,2016-01-12 01:50:58,2016-01-12 15:50:58,0,11, 0,0,0,0,25250,NO,NO,NO,61543261,1056.gz

答案 2 :(得分:0)

这是我的awk-oneliner,至少可以处理您提供的数据

awk '{ split($0, fields, ","); split($0, parts, "NO,NO,NO,"); printf "%s%s%s,%s\n", parts[1], "NO,NO,NO,", fields[3], parts[2] }'
  1. 使用逗号作为分隔符将记录拆分成多个部分,以提取第三个字段
  2. 再次分割记录,这次使用“ NO,NO,NO”作为分隔符
  3. printf归纳起来:在NO,NO,NO,NO,NO,NO之前的部分,然后是第三字段的副本以及记录的其余部分

如前所述,如果前两个字段中用引号引起来,它可能会引发问题...