Compare strings between 2 arrays and print number in AWK

Hi to everyone,

Please some help over here.

Hi have array a with 6 elements and array b with 3 elements as shown inside BEGIN{} statement.

I need help to get the correct sintax (the part in red) to compare if string from array b is in array a and print the number
related for each match.

awk 'BEGIN{
    a[1]="4|Mike F"
    a[2]="7|John M"
    a[3]="3|Carl L"
    a[4]="8|Mike F"
    a[5]="5|John M"
    a[6]="9|Carl L"
    
    b[1]="Carl L"
    b[2]="John M"
    b[3]="Mike F"}
{    
for ( j=1; j<=length(b); j++ ) { 
    
        if(a[j] ~ b[j]) {  # this is only the idea, I don't know the correct syntax
            print Number     
        }    
    }        
}'

E.g. If b[1]="Carl L" is in array a, then print
3
9

for b[2]="John M" print
7
5

and for b[3]="Mike F" print
4
8

I need to do this in awk because the loop will be part of a main awk code. In this sample only 2 occurences of b are in a,
but b values could be many times in a, so I need to print all matches for each value in b.

Many thanks in advance,

Grettings

Try this...

awk 'BEGIN{
    a[1]="4|Mike F"
    a[2]="7|John M"
    a[3]="3|Carl L"
    a[4]="8|Mike F"
    a[5]="5|John M"
    a[6]="9|Carl L"
    b[1]="Carl L"
    b[2]="John M"
    b[3]="Mike F"
}
{
  for(j in b){
    for(i=1;i<=length(a);i++){
      if(b[j] ~ a){
        split(a,arr,"|")
        print arr[1]
      }
    }
  }
}'

--ahamed

1 Like

Hi again ahamed,

Thanks for all your help. Learning from you. As usual it works!

Many thanks.

Grettings

You are welcome! :slight_smile:

--ahamed