Compare two files and send common strings to another file

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
navanees
Posts: 11
Joined: 20 Jul 2016 16:31

Compare two files and send common strings to another file

#1 Post by navanees » 19 Sep 2016 18:23

I have two text files and wanted to compare them and send the common strings to another file
There will be only one word per line. Strings can appear in any order, so it is not a line to line comparison.

I have sample files and the expected output attached below.
Please can someone help me with .bat script? Is is there a script already built for this?

FILE1 with the below strings

Pet
brown
spray
Pet
country
jack
tip
Ball
basket
magic
whistle
cry
bag
headphone
paper
mourn
eyebrow
mental
monster
google
schedule
mountain
bottle
hint
notice

File 2 with below strings

basket
schedule
mouse
ostrich
bag
brown
basket
chair
result
fantasy
tip
hint
hurt
shirt
notice
jack
white
crack
noble
deck
cover
spray


Output file

bag
notice
spray
schedule
hint
jack
brown
tip

misol101
Posts: 456
Joined: 02 May 2016 18:20

Re: Compare two files and send common strings to another file

#2 Post by misol101 » 19 Sep 2016 18:39

Straight from command line, you could do:

(for /F "tokens=*" %a in (file1) do @for /F "tokens=*" %b in (file2) do @if "%a"=="%b" echo %a)>outfile

Aacini
Expert
Posts: 1669
Joined: 06 Dec 2011 22:15
Location: México City, México

Re: Compare two files and send common strings to another file

#3 Post by Aacini » 19 Sep 2016 20:03

Code: Select all

findstr /G:file2 file1 > output

In your output example the "basket" string is missing...

Antonio

navanees
Posts: 11
Joined: 20 Jul 2016 16:31

Re: Compare two files and send common strings to another file

#4 Post by navanees » 19 Sep 2016 22:05

Acini,
findstr /G:file2 file1 > output ... it worked as expected.

Yes, basket was missing .. thanks for your response, appreciate it !!!

Post Reply