'read numbers from one file and search for them in another using awk script
I have 2 files, a.txt and b.txt, both of them are composed of numbers, one per line. What I'm trying to do is to read each number from a.txt, and search for it in b.txt. Here is the awk script file I wrote, I can execute this search.awk file like this,
awk -f search.awk a.txt
but how to search for each number in b.txt?
#!/bin/awk -f
{
print $1
# how to search for $1 in b.txt?
}
UPDATE
What if there is not only 1 file to be searched, there are multiple files in a dir to be searched for each number in a.txt? I mean that, search all those files in a_dir/* for each number in a.txt?
Solution 1:[1]
Stash lines from a.txt into an array and print those lines from b.txt that occur in the array
awk 'NR == FNR{a[$0]; next} $0 in a' a.txt b.txt
EDIT: If there are multiple files to be searched, this version prints the match file name and line
awk 'NR == FNR{a[$0]; next} $0 in a{print FILENAME, $0}' a.txt b.txt c.txt
Solution 2:[2]
Code example for awk:
awk 'NR==FNR {a[$1]=$1;next} $1==a[$1] && $1!=""' a.txt b.txt
$ cat a.txt
1
3
5
7
9
11
13
$ cat b.txt
1
4
7
10
13
$ cat c.txt
3
11
$ awk 'NR==FNR {a[$1]=$1;next} $1==a[$1] && $1!=""' a.txt b.txt c.txt
1
7
13
3
11
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
