Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare files with a CMD

I want to compare 2 files (comparing the size) with a CMD-batchfile. If files are not equal I want to start a copy-action, not from the command-line but in a batchfile.

I want to suppress thew question "Compare more files? " Is it not Echo N in front of the Comp-command ? Moreover I'm not totally convinced of my ">Nul" statement.

I tried:

@echo off
:main
Echo n comp  g:\test.accdb g:\test21.accdb >nul
if errorlevel 1 goto different size
:next
echo Files are same size
pause
exit

:different size
copy g:\test.accdb g:\test21.accdb
pause
EXIT
like image 542
Jan Steeg Avatar asked Sep 06 '25 04:09

Jan Steeg


2 Answers

FC File1.txt File2.txt >NUL && Echo Same || Echo Different or error

Errorlevels

FC will set an ErrorLevel as follows:

-1 Invalid syntax (e.g. only one file passed)
0 The files are identical.
1 The files are different.
2 Cannot find at least one of the files.
For an invalid switch (with two passed files) an error message is 
printed but the errorlevel is not changed.

Further reading http://ss64.com/nt/fc.html

like image 144
Paul Avatar answered Sep 09 '25 01:09

Paul


Technically the example provided in the answer from @Paul performs as expected, however if you intend to use anything more complex than Echo commands you need to understand what's happening before adopting it to your own situation. (I would also have mentioned this in a comment to his answer but I don't have enough reputation points.)

Given a command line of:

Command1 && Command2 || Command3

If Command1 fails then Command3 will be executed.

If Command1 succeeds then Command2 will be executed. But...if Command2 fails then Command3 will also be executed.

This is demonstrated below where I've chained together three FIND commands that search a file containing capital-letter keywords and altered the case of the string being sought accordingly. Note that the last example executes all three commands.

C:\Temp>find "select" test.txt && find "FROM" test.txt || find "WHERE" test.txt

---------- TEST.TXT

---------- TEST.TXT
WHERE            (

C:\Temp>find "SELECT" test.txt && find "FROM" test.txt || find "WHERE" test.txt

---------- TEST.TXT
SELECT           dbo.SalProductClass.ProductClass               ,

---------- TEST.TXT
FROM             dbo.SalProductClass

C:\Temp>find "SELECT" test.txt && find "from" test.txt || find "WHERE" test.txt

---------- TEST.TXT
SELECT           dbo.SalProductClass.ProductClass               ,

---------- TEST.TXT

---------- TEST.TXT
WHERE            (

C:\Temp>

That said, as the original poster does want an Echo command as Command2 his batchfile could be rewritten as follows:

@echo off
:main
FC g:\test.accdb g:\test21.accdb >nul && echo Files are same size || goto different size
pause
exit

:different size
copy g:\test.accdb g:\test21.accdb
pause
EXIT
like image 33
Wayne Ivory Avatar answered Sep 09 '25 02:09

Wayne Ivory