如何在批处理文件中比较两个文件?

19

我该如何在批处理文件中比较两个文件,并根据它们是否匹配执行操作?我尝试过类似以下的代码:

if file1.txt NEQ file2.txt goto label

但它比较的是实际字符串"file1.txt"而不是文件。我已经了解了COMP命令,但如果我将其放在if语句中,它似乎无法工作。有没有人知道怎么做?对不起,我很少使用批处理文件,对它们的经验很少。

先行致谢。

3个回答

36

我建议检查错误级别2,这表示出现了问题(其中一个文件无法打开,磁盘错误等)。 - LogicDaemon
你能澄清一下吗——errorlevel 0 是指相同,errorlevel 1 是指不同吗?还是反过来? - Craig McQueen
4
命令行参考中获取:"-1: 无效的语法(例如,只传递一个文件);0: 文件相同;1: 文件不同;2: 至少找不到其中一个文件。" - Linkyu

4

看起来 COMP 程序实际上相当容易使用。请参见 Yahoo 答案中的 this question

请注意,运行 comp /? 将打印该程序的帮助文本(任何本机 Windows 命令行程序都可以指定 /? 参数进行)。这会输出您在上面链接的问题答案中看到的相同文本。

来自 Yahoo 答案的内容:

C:\>comp /? 
Compares the contents of two files or sets of files. 

COMP [data1] [data2] [/D] [/A] [/L] [/N=number] [/C] [/OFF[LINE]] 

data1 Specifies location and name(s) of first file(s) to compare. 
data2 Specifies location and name(s) of second files to compare. 
/D Displays differences in decimal format. 
/A Displays differences in ASCII characters. 
/L Displays line numbers for differences. 
/N=number Compares only the first specified number of lines in each file. 
/C Disregards case of ASCII letters when comparing files. 
/OFF[LINE] Do not skip files with offline attribute set. 

To compare sets of files, use wildcards in data1 and data2 parameters.

1
注意那个答案的评论者,comp 存在一个问题:在每次比较之后,它会交互式地询问用户是否要继续比较其他文件。而且没有关闭该查询的开关,所以最好的选择是 echo N|comp file1 file2。否则,comp 更快,因为它首先比较大小,并在显示出10个不同之后停止比较,可以使用掩码比较文件组。另一方面,FC 显示所有差异并尝试在不同偏移量上重新同步相似之处(如 Unix diff),即使文件大小相同也会进行全文件比较。 - LogicDaemon
@LogicDaemon 有一个开关可以停止提示更多的文件。 /M 不提示比较更多的文件。 - tiboo
1
@tiboo 它只出现在一些最近的 Windows 10 版本中,我猜至少是在2019年。 - LogicDaemon

0

我使用以下示例基于文件差异构建报告:

set %Batch_Work_Space_Dir%=folder for your batch file and temp resource files
set file_1=name of file
set file_2=name of file

fc %file_1% %file_1%t > %Batch_Work_Space_Dir%\Are_They_Different.txt

powershell -command "(Get-Content %Batch_Work_Space_Dir%\Are_They_Different.txt) | select -skip 1 | Set-Content %Batch_Work_Space_Dir%\Are_They_Different.txt"
set /p Diff_Found=<%Batch_Work_Space_Dir%\Are_They_Different.txt
if %Diff_Found:~0,17%" == "FC: no difference" (
  execute commands
 )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接