简体   繁体   English

合并Linux上的两个文件,只保留两个文件中出现的行

[英]Merge two files on Linux keeping only lines that appear in both files

In Linux, how can I merge two files and only keep lines that have a match in both files? 在Linux中,如何合并两个文件并仅保留两个文件中匹配的行?

Each line is separated by a newline ( \\n ). 每一行用换行符分隔( \\n )。

So far, I found to sort it, then use comm -12 . 到目前为止,我发现要对它进行sort ,然后使用comm -12 Is this the best approach (assuming it's correct)? 这是最好的方法(假设它是正确的)?

fileA contains fileA包含

aaa
bbb
ccc
ddd

fileB contains fileB包含

aaa
ddd
eee

and I'd like a new file to contain 我想要一个新文件包含

aaa
ddd

Provided both of your two input files are lexicographically sorted , you can indeed use comm : 如果您的两个输入文件都按字典顺序排序 ,您确实可以使用comm

$ comm -12 fileA fileB > fileC

If that's not the case, you should sort your input files first: 如果不是这样,您应该首先sort输入文件进行sort

$ comm -12 <(sort fileA) <(sort fileB) > fileC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM