将特定列添加到CSV文件的末尾

时间:2014-12-31 04:57:27

标签: linux bash

可以用bash执行以下过程吗?

"Id";"Vzor";"Name";"Number";"Number2";"Ship"
"00041534";"MGKHTYE";"2014 TREK TYAX EXPERT, GREY/YELLOW";"100";"100,30";"A"
"00041535";"MGKHTYE";"2014 TREK TYAX EXPERT 29 , BLACK/RED";"100";"453,30";"A"
"00041531";"MGKHTYSP";"2014 OPS TYAX SPORT, WHITE/GREY";"100,90";"306,60";"A"
"00046024";"MGKFAR";"2015 OPS ARGUS, DARK TEAL";"899,90";"100,90";"A"
"00046088";"MGKHFB";"2015 TREK FIREBALL 24  , BLACK";"100,90";"239,90";"A"
"00046026";"MGKHFB";"2015 OPS FIREBALL 26 , BLUE";"100,90";"359,90";"A"

将一列添加到名为“Category”的第一行和(我不能做的)各个行,从第3列添加该列的前两个单词(这将是类别名称):

"Id";"Vzor";"Name";"Number";"Number2";"Ship";"Category"
"00041534";"MGKHTYE";"2014 TREK TYAX EXPERT, GREY/YELLOW";"100";"100,30";"A";"2014 TREK"
"00041535";"MGKHTYE";"2014 TREK TYAX EXPERT 29 , BLACK/RED";"100";"453,30";"A";"2014 TREK"
"00041531";"MGKHTYSP";"2014 OPS TYAX SPORT, WHITE/GREY";"100,90";"306,60";"A";"2014 OPS"
"00046024";"MGKFAR";"2015 OPS ARGUS, DARK TEAL";"899,90";"100,90";"A";"2015 OPS"
"00046088";"MGKHFB";"2015 TREK FIREBALL 24  , BLACK";"100,90";"239,90";"A";"2015 TREK"
"00046026";"MGKHFB";"2015 OPS FIREBALL 26 , BLUE";"100,90";"359,90";"A";"2015 OPS"

猛击力量!

1 个答案:

答案 0 :(得分:5)

您可以使用此awk命令:

awk 'BEGIN{FS=OFS=";"}
   NR==1{print $0,"\"Category\"";next} {
   split($3, a, " ");
   printf "%s%s%s %s\"\n", $0, OFS, a[1], a[2]
}' file

"Id";"Vzor";"Name";"Number";"Number2";"Ship";"Category"
"00041534";"MGKHTYE";2014 TREK TYAX EXPERT, GREY/YELLOW;"100";"100,30";"A";"2014 TREK"
"00041535";"MGKHTYE";2014 TREK TYAX EXPERT 29 , BLACK/RED;"100";"453,30";"A";"2014 TREK"
"00041531";"MGKHTYSP";2014 OPS TYAX SPORT, WHITE/GREY;"100,90";"306,60";"A";"2014 OPS"
"00046024";"MGKFAR";2015 OPS ARGUS, DARK TEAL;"899,90";"100,90";"A";"2015 OPS"
"00046088";"MGKHFB";2015 TREK FIREBALL 24  , BLACK;"100,90";"239,90";"A";"2015 TREK"
"00046026";"MGKHFB";2015 OPS FIREBALL 26 , BLUE;"100,90";"359,90";"A";"2015 OPS"

<强>解释

  • BEGIN{FS=OFS=";"}将输入和输出字段分隔符设置为;
  • NR==1仅对记录#1执行此块
  • {print $0,"\"Category\"";next}打印记录和文字"Category"
  • split($3, a, " ")按空格分割字段#3并使用单个字填充数组a
  • printf通过从数组a
  • 获取2个第一个单词来打印格式化输出