I have two files. The first is unip.txt and the second is ipex.txt and each file contains IP addresses.



I'm trying to figure out how to basically search the unip.txt file to see if it contains any IP from the ipex.txt file. I imagine that it would be a loop to search through every line, but I'm not sure how to do it.

2 Answers 2


This feature is built into grep. Use the -f option:

grep -Fx -f ipex.txt unip.txt

That prints all matches. If you are only interested in a yes/no answer, use the -q option ("quiet"):

if grep -Fxq -x -f ipex.txt unip.txt; then
    echo unip.txt contains IP addresses from ipex.txt
    echo "unip.txt doesn't contain IP addresses from ipex.txt"

Why -F? By default, grep interprets the lines in ipex.txt as regular expressions, and the dots in those lines have the meaning of "any character". This can (and likely will) lead to false matches. -F ensures that constant strings, not regular expressions, are matched.

Why -x? It ensures that IP addresses are matched to whole lines in unip.txt, thereby preventing partial matches, e.g. preventing from matching an address


An alternative approach I like for this type of problem is the comm command. It's useful to compare two files and determine (1) the lines found only in file1, (2) the lines found only in file2, and (3) the lines found in both files. The only downsides are that both input files need to be sorted, and it matches exact lines (i.e., doesn't look for substrings within a line).

I saved your examples as unip.txt and ipex.txt, sorted them using sort, then ran comm unip.txt ipex.txt. The output:

The output has three tab-delimited columns, corresponding to points (1), (2), and (3) that I made above. You can suppress the output of a column like so: comm -1 unip.txt ipex.txt. That command would not print the first column.

So, overall, to answer your question you need to sort your input files and then run comm -12 unip.txt ipex.txt, which will suppress the first two columns of output and then print the lines found in both files:

Hope this helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .