Awk - Create a key from line 01, fields $4$3$2 and line 07 $4

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Awk - Create a key from line 01, fields $4$3$2 and line 07 $4

High-T
Desired Matching Key: $4$3$2 from line 01 and $4 from line 07 of A.txt

Example: In A.txt $4=5000, $3=68, $2=89 in line 01 and $4=RT0429 or RT0428 or RT0588 in line 07. The matching key in B.txt is 50006889RT0428

Issue: I am looking to create a match key from File1.txt and match against File2.txt first 14 characters.

Details: A.txt line starting with 01 (column $4 $3 $2) and line starting with 07 (Column $4) combination is making a key = 50006889RT0428
which is the same as 50006889RT0428 in B.txt string first 14 characters.
I am putting if
Key Matched = A.txt line 01 - 07 and 77 tab matched string from B.txt
Key not Matched = A.txt line 01 - 07 and 99 after.

THE ISSUE IS I AM NOT ABLE TO CREATE A KEY FROM A.TXT LINES.


A.txt (input)

01  89  68  5000
02  83  11
07  83  11  RT0429
07  83  09  RT0428
07  88  10  RT0588
01  44  73  8800
06  44  73
07  44  11  RT0789

B.txt (input)

50006889RT0428 CCARD /3010  /E     /C A87545457          /  //                ///11        ///

51002387 CCARD /3000  /E     /S N054896334IV          /  //                ///11        ///

51002390800666 CCARD /3000  /E     /S N0978898IV          /  //                ///11        ///


X.txt (Desired Output)

01  89  68  5000
02  83  11
07  83  11  RT0429
07  83  09  RT0428
07  88  10  RT0588
77 50006889RT0428 CCARD /3010  /E     /C A87545457          /  //                ///11        ///
01  44  73  8800
06  44  73
07  44  11  RT0789
99

Script I am using

awk '
  BEGIN {
    OFS="\t"
    out = "X.txt"
    err = "Y.txt"
  }
  NR==FNR && NF {line[$1]=$0; next}
  function print_77_99() {
    if (key in line)
      print "77", line[key] > out
    else {
      print "99", date > out
      printf "%s", lines >> err
    }
  }
  $1 == "01" {
    if (FNR > 1) print_77_99()
    key = $4 $3 $2
    lines = ""
  }
  {
    print > out
    lines = lines $0 "\n"
  }
  END {print_77_99()}
' A.txt B.txt