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",,";
}