1

I have 2 files which contain IP addresses

1st File:

192.168.1.1:4.4.4.4
192.168.1.2:4.4.2.2
192.168.1.1:8.8.8.8
4.4.8.8:192.168.1.6
192.168.1.4:4.4.8.8

2nd file:

4.4.2.2
4.4.8.8

Now I want a script which takes each value from file 2nd and checks and if that values is present in files 1st. If the value is present it should print the entire line from file 1st.

For example desired result from above example:

192.168.1.2:4.4.2.2
4.4.8.8:192.168.1.6
192.168.1.4:4.4.8.8
1
  • 1
    Should the line be printed if the IP address occurs in either of the two :-delimited fields? ... or just in the second field? Is the order of the lines in the output significant?
    – Kusalananda
    Jun 7, 2019 at 19:31

2 Answers 2

0
grep -F -f file2.txt file1.txt

This will read the lines in file2.txt and use them as patterns to search for in file1.txt.


If you want to only check for matches in the second column you could use this awk command:

awk -F: 'NR==FNR{a[$0];next}$2 in a' file2.txt file1.txt

This will read each string from file2.txt and create an array (a) with them. It will then go through file1.txt and check if the value in column 2 exists in the a array. If it does, the whole line will be printed.

2
  • Hi Jesse, If possible could you also share the code if just want to print the line from file 1st which just matches the second value after ":" that is 192.168.1.2:4.4.2.2 and 192.168.1.4:4.4.8.8
    – user334662
    Jun 7, 2019 at 19:42
  • 1
    Thank You jesse for the help :)
    – user334662
    Jun 7, 2019 at 20:01
0

You can loop through second file and grep from first file.

for pattern in `cat file2.txt` ; do grep $pattern file1.txt ; done

If you want to match just the end after colon.

for pattern in `cat file2.txt` ; do grep :$pattern$ file1.txt ; done
1
  • Thank You soo much for the help :)
    – user334662
    Jun 7, 2019 at 20:01

You must log in to answer this question.

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