Skip to content
Advertisement

Add a column from one file into another file using AWK for a given condition [closed]

First of all, thank you for your help. I have 2 files which are

1   10
2   20
3   30
4   10
5   20

And

A   10
B   20
C   30

I wanto to filter both files using AWK so the if $2 in the first file is equal to the value of $2 in the second file the output will be adding a new column which matches the condition given:

 1  A   10  
 2  B   20  
 3  C   30
 4  A   10  
 5  B   20  

I have tried this code:

awk 'FNR==NR{a[NR]=$0;next}{$2=a[FNR]}1' letters.txt numbers.txt >> combined.txt

The problem is that the code only replace one column for the other I want to that the column matches the condition I have given above. Also I want to put the new column between the columns from number.txt file

Advertisement

Answer

The following might work for you:

awk '
     NR == FNR { m[$2]=$1;   next }
     $2 in m   {    $3=m[$2]      }
     1
' letters.txt numbers.txt
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement