Abhishek
Abhishek

Reputation: 279

awk to match pattern from a file to another file

To find a string in a file and print first column of the output, we can use

grep "foo" file.txt | awk '{print $1}' which can be done using awk alone

awk '/foo/ {print $1}' file.txt (https://stackoverflow.com/a/22866418/1662898).

Instead of a single string (foo) as a pattern, I want to search for a list of strings in a file. Using grep, it would be

grep -f file.txt file2.txt | awk '{print $1}' > outFile.txt

Can I do the same using awk alone?

file.txt
abcd
acde
a2rt

file2.txt
1 albcd dhakd kdf
3 abcdbd and
2a bda2rt tert

outFile.txt
3
2a

Thanks! Abhishek

Upvotes: 3

Views: 9941

Answers (1)

anubhava
anubhava

Reputation: 784898

Equivalent awk command will be this one:

awk 'NR==FNR{a[$1]; next} {for (i in a) if (index($0, i)) print $1}' file.txt file1.txt

Output:

3
2a

Using non-regex string comparison (index($0, i)) instead of a regex match ($0 ~ i) because of -F option of grep.

Upvotes: 5

Related Questions