Page 1 of 1

Compare two files and send common strings to another file

Posted: 19 Sep 2016 18:23
by navanees
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

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

Posted: 19 Sep 2016 18:39
by misol101
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

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

Posted: 19 Sep 2016 20:03
by Aacini

Code: Select all

findstr /G:file2 file1 > output

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

Antonio

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

Posted: 19 Sep 2016 22:05
by navanees
Acini,
findstr /G:file2 file1 > output ... it worked as expected.

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