5

I want to find every line of a file that contains any of the strings held in a column of a different file.

I have tried
grep "$(awk '{ print $1 }' file1.txt)" file2.txt
but that just outputs file2.txt in its entirety.

I know I've done this before with a pattern I found on this site, but I can't find that question anymore.

1
  • The command in the OP does what it is supposed to. My problem was that file1 had a blank line which was sending the pattern "" to grep, causing it to find every line in file2. Commented Apr 27, 2011 at 19:57

3 Answers 3

10

I see in the OP's comment that maybe the question is no longer a question. However, the following slight modification will handle the blank line situation. Just add a check to make sure the line has at least one field:

grep "$(awk '{if (NF > 0) print $1}' file1)" file2

And if the file with the patterns is simply a set of patterns per line, then a much simpler version of it is:

grep -f file1 file2

That causes grep to use the lines in file1 as the patterns.

Sign up to request clarification or add additional context in comments.

Comments

2

THere is no need to use grep when you have awk

awk 'FNR==NR&&NF{a[$0];next}($1 in a)' file2 file1

Comments

0

$(awk '{ print $1 }' file1.txt) | grep text > file.txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.