Operating System - HP-UX
1834022 Members
2256 Online
110063 Solutions
New Discussion

How to select common entry between two files

 
SOLVED
Go to solution
Abhijeet_3
Frequent Advisor

How to select common entry between two files

Suppose I have two file which contents are as follow

$cat file1
user1
user2
user3
user4

$cat file2
user1
user3
user5
user7
user10

I need how to select common fileld between these 2 file ( i.e. in this example user1 & user3 are common in both file )

Thx
Abhijeet
6 REPLIES 6
Devender Khatana
Honored Contributor
Solution

Re: How to select common entry between two files

Hi,

#comm -12 file1 file2

Man comm for details.

HTH,
Devender
Impossible itself mentions "I m possible"
Fred Ruffet
Honored Contributor

Re: How to select common entry between two files

list content of files,
sort it,
keep only duplicates.

Translated in shell :

cat file1 file2 | sort | uniq -d

Regards,

Fred
--

"Reality is just a point of view." (P. K. D.)
Muthukumar_5
Honored Contributor

Re: How to select common entry between two files

You can try as,

grep -f <

There is a problem that file1 has to be less or equal lines with file2. You can try with script as,

#!/bin/ksh

FILE1=file1
FILE2=file2

if [[ $(wc -l ${FILE1} |cut -d" " -f1) -lt $(wc -l ${FILE2} |cut -d" " -f1) ]]
then
grep -f ${FILE1} < ${FILE2}
else
grep -f ${FILE2} < ${FILE1}
fi

hth.
Easy to suggest when don't know about the problem!
Muthukumar_5
Honored Contributor

Re: How to select common entry between two files

Khatana,

Can you try and solve with comm command?

-- file1 --
user1
user2
user3
user4
user10
user11

-- file2 --
user1
user3
user5
user7
user10

# comm -12 file2 file1
user1
user3

# comm -12 file1 file2
user1
user3

grep + script is working and sort file1 file2 | uniq -d is also working.

hth.
Easy to suggest when don't know about the problem!
Abhijeet_3
Frequent Advisor

Re: How to select common entry between two files

Thx all of you.

Abhijeet
Abhijeet_3
Frequent Advisor

Re: How to select common entry between two files

Thx