0

I have two files

file1

159211;exampleimage002.JPG
159212;example.jpg
159212;example with space.jpg
...

file2

13;"OVET";"O1";"OVET/ULKO-OVET";159212;"JELDWEN BASIC 0015 9*21 VASEN";"KPL";1;345;1;0;"Toinen testituote";
13;"OVET";"O1";"OVET/ULKO-OVET";159211;"JELDWEN BASIC 0015 9*21 OIKEA";"KPL";1;345;1;0;"Myös rivinvaihdot siirtyvät";
...

What I need is to add the image names as a new column, multiple image files separated with "|". ID must match, for example 159212 (file1 first column and file2 5th column). I tried this using awk, but failed miserably.

Wanted output (file3), only difference is the last column:

13;"OVET";"O1";"OVET/ULKO-OVET";159212;"JELDWEN BASIC 0015 9*21 VASEN";"KPL";1;345;1;0;"Toinen testituote";"exampleimage002.JPG";
13;"OVET";"O1";"OVET/ULKO-OVET";159211;"JELDWEN BASIC 0015 9*21 OIKEA";"KPL";1;345;1;0;"Myös rivinvaihdot siirtyvät";"example.jpg|example with space.jpg";
0

How about

awk -F\; '
  NR==FNR {
    if (a[$1]=="") {
      a[$1]="\""$2
    } else {
      a[$1]=a[$1]"|"$2
    }
    next;
  }
  {
    print $0 a[$5] "\""
  }
  ' file1 file2 > file3

Note: this assumes there's at least one match for each ID - otherwise you'll likely get a spurious trailing close quote. If that's an issue, you could add a test for non-emptyness of a[$5] before printing.

  • This works, I added a test to check non-emptyness too, thanks! – SamSwampwater Sep 8 '16 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.