Extracting lines from text files in folder based on the numbers in another file

Hello,

I have a file ff.txt that looks as follows

*ABNA.txt
356
24
36
112
*AC24.txt
457
458
321
2

ABNA.txt and AC24.txt are the files in the folder named foo1. Based on the numbers in the ff.txt file, I want to extract the lines from the corresponding files in the foo1 folder and create new files with the existing file names in another folder foo2.
If the third or fourth column of ABNA.txt file contain 356,24,36,112 numbers, extract the lines and save it to another folder foo2 as ABNA.txt.

ABNA.txt file in the folder foo1 looks as follows

dfg  qza  356  245
hjb  hkg  455  24
ghf  qza  12   123
dfg  qza  36   55

AC24.txt file in the folder foo1 looks as follows

hjb  hkg  457  167
ghf  qza  2       165
sar  sar  234  321
dfg  qza  345  345

Output:

ABNA.txt file in the folder foo2

dfg  qza  356  245
hjb  hkg  455  24
dfg  qza  36     55

AC24.txt file in the folder foo2

hjb  hkg  457  167
ghf  qza  2        165
sar  sar   234  321

Try something like:

cd foo1
awk '
  NR==FNR{
    if(NF>1)f=$2
    else A[f,$1]
    next
  }
  (FILENAME,$3) in A || (FILENAME,$4) in A {
    print > ( todir "/" FILENAME )
  }
' todir=/path/to/foo2 FS=\* /path/to/ff.txt FS=" " *
1 Like

hi scrutinizer,

Excellent!! code works well. Thank you so much for your help!!