summer
summer

Reputation: 149

DOS batch program for file comparison

I have two text files , file1 and file2. I want to identify which lines in file2 are not there in file1. How can I do this using a DOS batch file?

Upvotes: 0

Views: 873

Answers (2)

Aacini
Aacini

Reputation: 67216

The Batch file below assume that there are not empty lines in any file.

@echo off
setlocal EnableDelayedExpansion

< file2 (
   set /P line2=
   for /F "delims=" %%a in (file1) do (
      set "line1=%%a"
      call :SeekNextLineInFile2ThatMatchThisLineInFile1
   )
   set "line1="
   call :SeekNextLineInFile2ThatMatchThisLineInFile1
)
goto :EOF

:SeekNextLineInFile2ThatMatchThisLineInFile1
   if not defined line2 exit /B
   if "!line2!" equ "%line1%" goto lineFound
   echo !line2!
   set "line2="
   set /P line2=
goto SeekNextLineInFile2ThatMatchThisLineInFile1
:lineFound
set "line2="
set /P line2=
exit /B

file1:

First line in both files
Second line in both files
Third line in both files
Fourth line in both files
Fifth line in both files

file2:

First line in file2 not in file1
First line in both files
Second line in both files
Second line in file2 not in file1
Third line in file2 not in file1
Third line in both files
Fourth line in both files
Fourth line in file2 not in file1
Fifth line in file2 not in file1
Fifth line in both files
Sixth line in file2 not in file1

Output:

First line in file2 not in file1
Second line in file2 not in file1
Third line in file2 not in file1
Fourth line in file2 not in file1
Fifth line in file2 not in file1
Sixth line in file2 not in file1

EDIT: New method added

The Batch file below does not require any order in the files. However, the files can not contain the equal-sign character and exclamation-marks are stripped. This process is not case sensitive, so two lines with same characters in different case are taken as equal.

@echo off
setlocal EnableDelayedExpansion

rem Read lines from file2
set i=100000
for /F "delims=" %%a in (file2.txt) do (
   set /A i+=1
   set "line[%%a]=!i:~-5!"
)

rem Remove lines from file1
for /F "delims=" %%a in (file1.txt) do (
   set "line[%%a]="
)

echo Result in sorted order:
for /F "tokens=2 delims=[]" %%a in ('set line[') do echo %%a

echo/
echo Result in original file2 order:
(for /F "tokens=2* delims=[]=" %%a in ('set line[') do echo %%bÿ%%a) > temp.txt
for /F "tokens=2 delims=ÿ" %%a in ('sort temp.txt') do echo %%a
del temp.txt

Upvotes: 0

MC ND
MC ND

Reputation: 70923

findstr /v /g:file1 file2

Use findstr, indicating strings to match should be taken from file1, search in file2, to show the lines in file2 that not match against strings in file1

Upvotes: 1

Related Questions