Sunday, July 10, 2022

[SOLVED] Using grep and awk together

Issue

I have a file (A.txt) with 4 columns of numbers and another file with 3 columns of numbers (B.txt). I need to solve the following problems:

  1. Find all lines in A.txt whose 3rd column has a number that appears any where in the 3rd column of B.txt.

  2. Assume that I have many files like A.txt in a directory and I need to run this for every file in that directory.

How do I do this?


Solution

Here is an example. Create the following files and run

awk -f c.awk B.txt A*.txt 

c.awk

FNR==NR {
    s[$3]
    next
}

$3 in s {
    print FILENAME, $0
}

A1.txt

1 2 3
1 2 6
1 2 5

A2.txt

1 2 3
1 2 6
1 2 5

B.txt

1 2 3
1 2 5
2 1 8

The output should be:

A1.txt 1 2 3
A1.txt 1 2 5
A2.txt 1 2 3
A2.txt 1 2 5


Answered By - slitvinov
Answer Checked By - Timothy Miller (WPSolving Admin)