Brinley
Brinley

Reputation: 721

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 (i.e. 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?

Upvotes: 0

Views: 89

Answers (1)

anubhava
anubhava

Reputation: 786011

You can use awk:

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

user3:animal

Upvotes: 2

Related Questions