user10254032
user10254032

Reputation: 193

print matched column from multiple inputs and concatenate the output

print matched column from multiple inputs and concatenate the output

A.lst

1091 1991    43.5   -30.1   -11.4
1091 1993   -11.2   -28.5    -2.7
1091 1997    35.8   -13.2    -4.5
1091 2003   -26.8   -23.9     0.6
1091 2007    23.8    64.8     3.5
1091 2008   -45.8    70.7    -6.0
1100 1967    24.5   -25.6   -12.7
1100 1971  -935.0     9.3    52.0
1100 1972  -388.8    59.1    20.4
1100 1974    17.7    48.9     3.0

B.lst

1091 1991 295 1
1091 1993 293 3
1091 1997 296 7
1091 2003 287 13
1091 2007 283 17
1091 2008 282 18
1100 1967 1419 3
1100 1971 56 7
1031 2023 283 17
1021 2238 282 18
1140 1327 1419 3
1150 3971 56 7
1100 1972 55 8
1100 1974 1445 10

By using this command (from previous, cant remember from where, i'll credit to them once i found it),

NR==FNR{ 
    a[$1,$2]=$1; next 
}
{ 
    s=SUBSEP
    k=$3 s $4
}k in a{ print $0 }

But I've no idea how to combine the output it should print only matched (certain column $3 $4 from B.lst)

1091 1991    43.5   -30.1   -11.4 295 1
1091 1993   -11.2   -28.5    -2.7 293 3
1091 1997    35.8   -13.2    -4.5 296 7
1091 2003   -26.8   -23.9     0.6 287 13
1091 2007    23.8    64.8     3.5 283 17
1091 2008   -45.8    70.7    -6.0 282 18
1100 1967    24.5   -25.6   -12.7 1419 3
1100 1971  -935.0     9.3    52.0 56 7
1100 1972  -388.8    59.1    20.4 55 8
1100 1974    17.7    48.9     3.0 1445 10

Upvotes: 1

Views: 60

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133670

Could you please try following.

awk 'FNR==NR{array[$1,$2]=$3 OFS $4;next} (($1,$2) in array){print $0,array[$1,$2]}'  file_B file_A

Adding a non-one liner form of above solution now.

awk '
FNR==NR{
  array[$1,$2]=$3 OFS $4
  next
}
(($1,$2) in array){
  print $0,array[$1,$2]
}
'  file_B file_A

Explanation: Adding explanation for above code.

awk '                        ##Starting awk program here.
FNR==NR{                     ##Checking condition FNR==NR which will be TRUE when file_B is being read.
  array[$1,$2]=$3 OFS $4     ##Creating an array named array whose index is $1,$2 and value is $3 OFS $4.
  next                       ##Using next will skip all further statements from here.
}                            ##Closing FNR==NR condition BLOCK here.
(($1,$2) in array){          ##Checking condition if $1,$2 is present in array then do following.
  print $0,array[$1,$2]      ##Printing current line and then value of array with index of $1,$2
}
'  file_B file_A             ##Mentioning Input_file names here.

Upvotes: 4

Related Questions