I have 2 files which contain IP addresses

1st File:

2nd file:

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:
  • 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 '19 at 19:31
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.

  • 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 and – user334662 Jun 7 '19 at 19:42
  • 1
    Thank You jesse for the help :) – user334662 Jun 7 '19 at 20:01

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
  • Thank You soo much for the help :) – user334662 Jun 7 '19 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.