compare two files line by line

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
ernst
Posts: 4
Joined: 10 Oct 2016 19:44

compare two files line by line

#1 Post by ernst » 10 Oct 2016 20:10

i would like to have file1 compared with file2, line by line, and then output results to file3, so the matching lines remain same but non-matching are replaced with -- for example.

Code: Select all

file1   file2   file3
01      01      01
02      02      02
03      04      --
04      04      04
00      05      --   

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: compare two files line by line

#2 Post by foxidrive » 10 Oct 2016 23:02

Questions for you.

1) Can the files have a differing number of lines?
2) Is the data always numerical?

ernst
Posts: 4
Joined: 10 Oct 2016 19:44

Re: compare two files line by line

#3 Post by ernst » 11 Oct 2016 03:51

1) no, both files have always same number of lines
2) yes, always numbers

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: compare two files line by line

#4 Post by foxidrive » 11 Oct 2016 04:30

Test this code:

Code: Select all

@echo off
(
< "file2.txt" (
   for /F "usebackq delims=" %%a in ("file1.txt") do (
      set file2Line=
      set /P file2Line=
      setlocal EnableDelayedExpansion   
      if %%a EQU !file2Line! (echo %%a) else (echo --)
      endlocal
   )
))>"newfile.txt"
pause

ernst
Posts: 4
Joined: 10 Oct 2016 19:44

Re: compare two files line by line

#5 Post by ernst » 11 Oct 2016 04:45

thank you! it works exactly as needed :)

ernst
Posts: 4
Joined: 10 Oct 2016 19:44

Re: compare two files line by line

#6 Post by ernst » 12 Oct 2016 20:04

please forgive me - i lied to you (see answer 2). because of my own stupidity i couldn't realize at first that hex (goal is to compare hex code) could be letters too. so was the previous success based only 1 test with few lines.

anyway, after trying this and that, script starts giving false results, until it sees everything being different (copy-paste,new files,restarts,etc doesn't help). maybe i used too long files (262144 lines in format of 2 digits or letters per line) at some point and something got stuck?

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: compare two files line by line

#7 Post by foxidrive » 13 Oct 2016 21:00

Change this if %%a EQU !file2Line!

to this if /i "%%a"=="!file2Line!"


and test it.

Post Reply