Adrian
Adrian

Reputation: 2656

Add specific column to the end of a CSV file

It is possible to do with bash the following process?

"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"

Add a column to the first row named "Category" and (what I can't do) to individual rows add from column 3 the first two word of that column (this will be the category name):

"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"

Bash power!

Upvotes: 1

Views: 65

Answers (1)

anubhava
anubhava

Reputation: 786291

You can use this awk command:

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"

Explanation:

  • BEGIN{FS=OFS=";"} Sets input and output field separator as ;
  • NR==1 Execute this block for record #1 only
  • {print $0,"\"Category\"";next} Print record and literal text "Category"
  • split($3, a, " ") to split field #3 by spaces and populate array a with individual words
  • printf prints formatted output by taking 2 first words from array a

Upvotes: 5

Related Questions