我该如何在批处理文件中比较两个文件,并根据它们是否匹配执行操作?我尝试过类似以下的代码:
if file1.txt NEQ file2.txt goto label
但它比较的是实际字符串"file1.txt"而不是文件。我已经了解了COMP命令,但如果我将其放在if语句中,它似乎无法工作。有没有人知道怎么做?对不起,我很少使用批处理文件,对它们的经验很少。
先行致谢。
我该如何在批处理文件中比较两个文件,并根据它们是否匹配执行操作?我尝试过类似以下的代码:
if file1.txt NEQ file2.txt goto label
但它比较的是实际字符串"file1.txt"而不是文件。我已经了解了COMP命令,但如果我将其放在if语句中,它似乎无法工作。有没有人知道怎么做?对不起,我很少使用批处理文件,对它们的经验很少。
先行致谢。
我认为您可以使用 "FC" 命令,然后检查 errorlevel。以下是一些代码:
@echo off
:main
fc c:\filename r:\filemame > nul
if errorlevel 1 goto error
:next
echo insert next CD
pause
goto main
:error
echo failed check
(从http://www.computing.net/answers/dos/batch-file-command/15753.html获取)
看起来 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.
comp
存在一个问题:在每次比较之后,它会交互式地询问用户是否要继续比较其他文件。而且没有关闭该查询的开关,所以最好的选择是 echo N|comp file1 file2
。否则,comp
更快,因为它首先比较大小,并在显示出10个不同之后停止比较,可以使用掩码比较文件组。另一方面,FC
显示所有差异并尝试在不同偏移量上重新同步相似之处(如 Unix diff),即使文件大小相同也会进行全文件比较。 - LogicDaemon/M 不提示比较更多的文件。
- tiboo我使用以下示例基于文件差异构建报告:
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
)