Domanda

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?

È stato utile?

Soluzione

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",,";
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top