Home > front end >  Merge two files AWK
Merge two files AWK

Time:10-10

I have to merge two files and need help with:

File1.csv

mac-test-2,10.57.8.2,Compliant
mac-test-6,10.57.8.6,Compliant
mac-test-12,10.57.8.12,Compliant
mac-test-17,10.57.8.17,Noncompliant

File2.csv

mac-test-17,10.57.8.17,2022-10-21

After Merge the content should be Merge.csv

mac-test-2,10.57.8.2,Compliant,NA
mac-test-6,10.57.8.6,Compliant,NA
mac-test-12,10.57.8.12,Compliant,NA
mac-test-17,10.57.8.17,Noncompliant,2022-10-21

so logic is if the File1.txt doesnt have a matching record in File2.txt then "NA" should be inserted and if it is a match then date should be inserted in the fourth column.

I have written below

awk -F "," '
ARGV[1] == FILENAME{a[$1];next}
{
 if ($1 in a) {  
    print $0 ","
 } else {
  print $0 ",NA"
 }
}
' File2.csv File1.csv

But this is printing

mac-test-2,10.57.8.2,Compliant,NA
mac-test-6,10.57.8.6,Compliant,NA
mac-test-12,10.57.8.12,Compliant,NA
mac-test-17,10.57.8.17,Noncompliant,

I am not sure how I can print the date if it matches.

CodePudding user response:

With your shown samples please try following awk code. Written and tested with your shown samples only.

awk '
BEGIN{ FS=OFS="," }
FNR==NR{
  arr[$1]=$NF
  next
}
{
  print $0,($1 in arr?arr[$1]:"NA")
}
' file2.csv file1.csv

To handle empty file2.csv please try following awk program.

awk '
BEGIN{ FS=OFS="," }
ARGV[1] == FILENAME{
  arr[$1]=$NF
  next
}
{
  if ($1 in arr) {
    print $0,arr[$1]
  }
  else{
    print $0,"N/A"
 }
}' file2.csv file1.csv
  • Related