2

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

unip.txt:

49.235.113.205
50.115.166.136
51.15.70.104
51.15.87.74
51.15.134.103
146.148.13.9
148.70.23.131
148.72.212.161
148.216.29.46
149.56.141.193

ipex.txt:

51.15.134.103
148.70.23.131
151.141.0.0
97.89.32.238

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

5

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
else
    echo "unip.txt doesn't contain IP addresses from ipex.txt"
fi

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 49.235.113.20 from matching an address 49.235.113.205.

0
3

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:

146.148.13.9
148.216.29.46
        148.70.23.131
148.72.212.161
149.56.141.193
    151.141.0.0
49.235.113.205
50.115.166.136
        51.15.134.103
51.15.70.104
51.15.87.74
    97.89.32.238

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:

148.70.23.131
51.15.134.103

Hope this helps!

You must log in to answer this question.

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