-2

Let me give the example text files :

e.g. in file1.txt The data is:-

qwer
asdf
zxcv
1234

in file2.txt The data is:-

0987
5678
uiop
qwer
zxcv

Desired result:

qwer
zxcv

How do I get this result? I want to use python or gawk or sed.

shobhit
  • 702
  • 2
  • 9
  • 21
Sam
  • 37
  • 1
  • 5
  • hi, we run this "comm -12 <(sort file1.txt) <(sort file1.txt)" ok in linux os, but windows 7 os fail,ths! in windows 7 os: sort file1.txt >out1.txt sort file2.txt >out2.txt comm -12 out1.txt out2.txt result pass – Sam Mar 07 '12 at 02:05

2 Answers2

6

I'd use Python sets for this:

file1 = set(line.strip() for line in open('file1.txt'))
file2 = set(line.strip() for line in open('file2.txt'))

for line in file1 & file2:
    if line:
        print line
wim
  • 338,267
  • 99
  • 616
  • 750
NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

Use comm:

comm -12 <(sort file1.txt) <(sort file2.txt)

With gawk:

gawk 'NR==FNR {file1[$0]++; next} $0 in file1' file1.txt file2.txt
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • comm -12 <(sort file1.txt) <(sort file2.txt), we use this command line show "The system can not find the file specified" and windows 7 os 64 bit – Sam Mar 06 '12 at 15:04