If statement compare two files.

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
jmair
Posts: 3
Joined: 30 Oct 2019 15:50

If statement compare two files.

#1 Post by jmair » 30 Oct 2019 15:57

I need a quick way to see if there is a different file, and if there is to copy said file and replace the first file.
The below works fine, however i'm not sure how to add the return into a variable. Any advice would be welcomed.
comp sample1.txt sample2.txt /m

penpen
Expert
Posts: 1995
Joined: 23 Jun 2013 06:15
Location: Germany

Re: If statement compare two files.

#2 Post by penpen » 31 Oct 2019 02:49

You could use a for/f loop to store the resulting output into a variable if that is what you want (untested):

Code: Select all

@echo off
setlocal enableExtensions disableDelayedExpansion
for /f "skip=1 tokens=* delims=" %a in ('comp sample1.txt sample2.txt /m') do (
	set "line=%~a"
)
Another option were to use the errorlevel (probably 1 if files are different, 0 else; untested):

Code: Select all

@echo off
setlocal enableExtensions disableDelayedExpansion
comp sample1.txt sample2.txt /m
if "%errorlevel%" == "1" (
	echo Do something if files are different.
) else if "%errorlevel%" == "0" (
	echo Do something if files are euqal.
)
penpen

jmair
Posts: 3
Joined: 30 Oct 2019 15:50

Re: If statement compare two files.

#3 Post by jmair » 31 Oct 2019 07:03

Penpen, thank you! You're a life saver. This works perfectly.

jmair
Posts: 3
Joined: 30 Oct 2019 15:50

Re: If statement compare two files.

#4 Post by jmair » 31 Oct 2019 15:00

Do you know if there is a way to NOT prompt in Windows 7? Win7 doesn't seam to have a /M argument with that version of comp.
I have 400 local machines (non domain) I need to put a batch file on to compare files and unfortunately about half of them are old windows 7 thin clients.

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: If statement compare two files.

#5 Post by aGerman » 31 Oct 2019 15:12

Give it a go:

Code: Select all

echo n|comp sample1.txt sample2.txt
Steffen

Post Reply