简体   繁体   中英

Pipe a file into grep and perform grep search with regex

Background:

I have the following list of keywords in keywords.txt:

animal
building
person

and the following list of fake users and passwords in users.txt:

user:animal@234
user2:animal234
user3:animal

I'd like to use grep to correlate the two files (ie search for an exact occurrence of each keyword in users.txt)

My first attempt ...

cat keywords.txt | grep -F -w -f- users.txt 

returned

user:animal@234
user3:animal

because grep -w will return lines in which the keyword is "followed a by non-word constituent character." Hence user:animal@234 was returned because the keyword "animal" followed by the non-word constituent character '@' was found.

I did some searching and found that grep ":animal$" users.txt returned the desired result:

user3:animal

because '$' is the regex symbol for end-of-line.

Problem:

I'm having trouble implementing a solution to search for all keywords, instead of just "animal."

Here's what I have so far:

while read line; do echo -n ":${line}$" | grep -F -f- users.txt; done < keywords.txt

Unfortunately, ^ this command returns nothing. It should return:

user3:animal

Any thoughts on what I should try?

You can use awk :

awk -F: 'NR==FNR{a[$1]; next} $2 in a' keywords.txt users.txt

user3:animal

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