遍历 txt 文件的内容以在第二个 txt 文件中找到匹配项(Mac OS 或 Linux)

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

搜索了网站,找不到我需要的东西。我有两个 .txt 文件,每个文件的每一行都有一个值,由换行符分隔。

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

在 Mac OS 或 Linux 中,如何遍历第一个 .txt 文件的每一行并在第二个 .txt 文件中找到相应的值?理想情况下,我想输出一个只显示找到的值的 final.txt。

感谢任何帮助!提前致谢!

您可以这样做,其中 a.txt 是左侧文件,b.txt 是右侧文件。 运行 在终端中,与文件所在的文件夹中:

for token in `cat a.txt`                                                      
do 
    grep $token b.txt
done

如果你想输出到一个文件中,那么你可以添加 tee 例如:

for token in `cat a.txt`
do 
    grep $token b.txt | tee -a final.txt
done
grep -o -f 1sttxtfile 2ndtxtfile >  final.txt

使用第一个文件的内容作为搜索词,通过使用 -f 标志在第二个文件中查找。仅打印匹配项 -o