1
votes

I am new to awk and trying to write code which can merge 2 files..

File1

session=123;1,code=01,name=om  
session=345;3,code=04,name=ra

File2

time=44,minute=22,sec=01,session=123;1,creation=89
time=34,minute=12,sec=023,session=523;1,creation=80

Output should be

time=44,minute=22,sec=01,session=123;1,creation=89,code=01,name=om
time=34,minute=12,sec=023,session=523;1,creation=80,,

I have written something like:

BEGIN { FS = OFS = "," }
FNR == NR {
  a[$2] = substr($0,index($0,$2));
  next
}
{
  if($4 in a)print $0","a[$2];
  else print $0",,";
}

But this does not generate the correct output.

Could you please help where I was mistaken?

1
Why isn't the rest of the line of file1 included in the expected output? Are there really supposed to be multiple session values on the same line in file1?Barmar
Because file2 is Base file.. if something extra in file1 then that can be ignored.. but I need everything from file2.Vipin Choudhary
My question was due to the incorrect formatting of file1 before you edited.Barmar
aha.. yes I edited that too..thanksVipin Choudhary

1 Answers

2
votes

index($0, $2) is not a good way to get everything after field 2. In the first line of file1, $2 is "1", so index($0, "1") finds the 1 in section=123.

Try this:

BEGIN { FS = OFS = "," }
FNR == NR {
  session=$1;
  $1 = "";
  a[session] = $0;
  next
}
{
  if($4 in a)print $0","a[$4];
  else print $0",,";
}