How to find the matching records from 2 files in unix

0

I have two files which contains email_ids. 1. Test1.txt 2. Test2.txt

Test1.txt contents are:

abc@gmail.com xyz@gmail.com mns@gmail.com

Test2.txt Contents are:

jpg@gmail.com joy@yahoo.com abc@gmail.com pet@yahoo.com

Here abc@gmail.com is common id between Test1.txt and Test2.txt. I want to find out such Id's from these 2 files and insert them into one file.

Please suggest. I just need the ID's which are common in between these two files.

Pooja25

Posted 2014-03-10T08:28:06.957

Reputation: 33

Answers

2

Try:

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

Scrutinizer

Posted 2014-03-10T08:28:06.957

Reputation: 249

+1 for idiomatic Awk :) Had to read it carefully :) I'm a bit surprised, though: are you sure Awk is obliged to create an entry for A[$1] given that there is no lvalue access (no assignment)? So the simple fact of indexing should create an entry? This would not be the case in Perl, but Awk's implementation may of course differ. – Edward – 2014-03-11T10:09:34.017

1

Hi @Edward-Baudrez, Yes I am certain of this. "The in operator, which tests for the existence of a particular array element, shall not cause that element to exist. Any other reference to a nonexistent array element shall automatically create it." See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/awk.html#tag_20_06_13_02

– Scrutinizer – 2014-03-11T18:09:54.710

So the use of $1 in A on the right-hand side is deliberate, otherwise that expression would also create array elements and that would not be desirable.. – Scrutinizer – 2014-03-11T18:15:55.807

@EdwardBaudrez: added this your name has a space. – Scrutinizer – 2014-03-11T18:42:26.057

1The (rather grandiose) term is "autovivification", also present though in different ways in perl. – mr.spuratic – 2014-03-11T20:30:56.593

@mr.spuratic: agree; what I wanted to say was that Perl would not create an array element in this particular case, because the element is not being assigned to – Edward – 2014-03-14T12:40:39.983

@mr.spuratic: On second thought, I'm not sure you can call it autovivification in Perl, because that is only for references. Assigning to a non-existent array element will simply extend that array if it is indexed beyond the end. – Edward – 2014-03-14T12:44:07.133

@Scrutinizer cool, thanks, that was insightful! – Edward – 2014-03-14T12:45:35.407

@Scrutinizer: my name used to have a space, indeed. I removed it. Did it cause any problems? – Edward – 2014-03-14T12:49:52.750

You're welcome @Edward . No, no problems, but since I am relatively new here, I did not know how to handle a space in the name, so I found out later, but then I could no longer edit my response.. – Scrutinizer – 2014-03-14T17:44:59.153