Search code examples
linuxmacosparsingtext-parsingtxt

Loop through contents of txt file to find match in 2nd txt file (Mac OS or Linux)


Searched the site and couldn't find what I need. I have two .txt files, each with a single value on each line separated by a linebreak.

1st TXT File 2nd TXT File
value1 value3
value2 value4
value3 value5
... value6
... value7
... value8

In Mac OS or Linux, how do I loop through every line of the 1st .txt file and find a corresponding value in the 2nd .txt file? Ideally, I'd like to output a final.txt that only shows the values that were found.

Any help is appreciated! Thank you in advance!


Solution

  • grep -o -f 1sttxtfile 2ndtxtfile >  final.txt
    

    Use the contents of the first file as search terms to find in the second file by using the -f flag. Print only the matches with -o