add rows from another file if the condition is true

You may use this enhanced awk script:

cat rnd.awk

function rnd(max) {           # generate a randon number between 2 and max
   return int(rand()*max-1)+2
}
function rndsum() {
   while(1) {                 # infinite loop
      r = rnd(NR)             # generate a randomm number between 2 and NR
      if (!seen[r]++)         # populate seen array with this random number
         s += num[r]          # get aggregate sum from num array

      if (s == sum)           # if sum then break the loop
         break
      else if (s > sum) {     # if s > sum then restart the loop
         delete seen
         s = 0
         continue
      }
   }
   for (j in seen)            # for each val in seen print rec array
      print rec[j]
   delete seen
   s = 0
}
BEGIN {
   srand()                    # seed random generation
}
NR == 1 {                     # for header row
   print                      # print header record
   next
}
FNR == NR {                   # while processing file1
   rec[NR] = $0               # save each record in rec array with NR as key 
   num[NR] = $NF              # save last column in num array with NR as key
   next
}
FNR > 1 {
   rec2[++n] = $0             # records in file2 being saved in rec2
}
END {
   rc = rc > n ? n : rc       # allow rc to be max of row count in file2
   for (i=1; i<=rc; ++i) {    # for 1..rc
      rndsum()               # print random rows from file1
      print rec2[i]           # print a row from file2
   }
   rndsum()                  #  print random rows from file1
}

Now use it as:

awk -v sum=7 -v rc=2 -f rnd.awk file1 file2 | column -t

cell  input        out  type  fun                level
IA2   A1,A2,A3     Z    comb  ((!A1A2)A3)        3
BUF   A1,A2,A3,B1  Z    comb  (!(((A1A2)A3)B1))  4
CLK   C            Z    seq   Cq                 1
IA2   A1,A2,A3     Z    comb  ((!A1A2)A3)        3
IAD   A1,A2,A3     Z    comb  (!((A1A2)A3))      3
INV   I1           ZN   comb  (!I1)              1
DFk   C,Cp         Q    seq   IQ                 1
XOR   A1,A2,B1     Z    comb  (((A1A2)B1)        3
IAD   A1,A2,A3     Z    comb  (!((A1A2)A3))      3
INV   I1           ZN   comb  (!I1)              1

and again:

awk -v sum=7 -v rc=1 -f rnd.awk file1 file2 | column -t

cell  input        out  type  fun                level
IAD   A1,A2,A3     Z    comb  (!((A1A2)A3))      3
BUF   A1,A2,A3,B1  Z    comb  (!(((A1A2)A3)B1))  4
CLK   C            Z    seq   Cq                 1
XOR   A1,A2,B1     Z    comb  (((A1A2)B1)        3
BUF   A1,A2,A3,B1  Z    comb  (!(((A1A2)A3)B1))  4

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top