简体   繁体   中英

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}' 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 -Ff 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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM