如何在unix中找到2个文件的匹配记录

问题描述 投票:2回答:2

我有两个包含email_ids的文件。 1. Test1.txt 2. Test2.txt

Test1.txt的内容是:

[email protected] [email protected] [email protected]

Test2.txt内容如下:

[email protected] [email protected] [email protected] [email protected]

这里[email protected]是Test1.txt和Test2.txt之间的通用id。我想从这两个文件中找出这样的Id并将它们插入到一个文件中。

请建议。我只需要在这两个文件之间常见的ID。

unix sed awk
2个回答
2
投票

尝试:

awk 'NR==FNR{A[$1]; next} $1 in A' file1 file2 > file.new

--edit:补充说明 -

awk '           
  NR==FNR {               # When the first file is being read (only then are FNR and NR equal)
    A[$1]                 # create an (associative) element in array A with the first field as the index 
    next                  # start reading the next record (line)
  }              
  $1 in A                 # while reading the second file, if field 1 is present in array A then print the record (line) 
' file1 file2 > file.new  # first read file1 as the first file and then file2 as the second file and write the output to a 3rd file.

3
投票

您也可以使用grep执行此操作:

grep -Fwf Test1.txt Test2.txt

$ head t*
==> t1 <==
[email protected]
[email protected]
[email protected]

==> t2 <==
[email protected]
[email protected]
[email protected]
[email protected]

$ grep -Fwf t1 t2
[email protected]
© www.soinside.com 2019 - 2024. All rights reserved.