Windows batch compare two files, showing only the exact lines that are different.
- User
Windows batch compare two files, showing only the exact lines that are different.
- Assistant
In a Windows environment, you can use a batch file to compare two files and show only the lines that are different. A common way to do this is by using a combination of commands like
FC(File Compare) and some text processing utilities.Here's a possible method using a batch file:
-
Create a batch file, for example,
compare_files.bat. -
Use the following script in
compare_files.bat:
@echo off setlocal set file1=%1 set file2=%2 if "%file1%"=="" ( echo Usage: compare_files file1 file2 exit /b 1 ) if "%file2%"=="" ( echo Usage: compare_files file1 file2 exit /b 1 ) fc %file1% %file2% > diff.txt for /f "usebackq tokens=1,* delims=:" %%A in (`findstr /n "^" %file1%`) do ( set "line=%%B" set "num=%%A" call :check_diff ) for /f "usebackq tokens=1,* delims=:" %%A in (`findstr /n "^" %file2%`) do ( set "line=%%B" set "num=%%A" call :check_diff ) del diff.txt goto :eof :check_diff setlocal enabledelayedexpansion findstr /b /c:"!num!" diff.txt >nul if %errorlevel% equ 0 ( findstr /b /c:"Ln !num!" diff.txt ) endlocal goto :eofExplanation:
-
Set Up Environment and Variables:
setlocal: Ensures the environment changes are local to this script.set file1=%1andset file2=%2: Assign command-line arguments tofile1andfile2.
-
Input Validation:
- Checks if both file parameters are provided. If not, it prints a usage message and exits.
-
Compare Files:
fc %file1% %file2% > diff.txt: Compares the files and stores the differences indiff.txt.
-
Processing File Lines:
- For each line in
file1andfile2, with line numbers, the loop processes the lines. findstr /n "^" %file1%andfindstr /n "^" %file2%: Prepares the lines prefixed with line numbers.
- For each line in
-
Checking Differences:
- For each line number,
:check_diffchecks if that line number appears indiff.txt. - If a difference is found (
findstrreturns 0), it prints the line fromdiff.txt.
- For each line number,
-
Clean Up:
- Deletes the
diff.txttemporary file.
- Deletes the
-
Subroutine for Checking Differences:
:check_diff: Subroutine to check differences.- Uses
findstrto look for line numbers in the differences file and prints them if found.
Running the Script:
To use the batch file, run it from the command line, passing the two files you want to compare as arguments:
compare_files.bat file1.txt file2.txtThis will print only the lines that are different between
file1.txtandfile2.txt.Notes:
- The script assumes that both files are text files and have line breaks.
- The output will show the exact lines that are different, prefixed by line numbers.
- Ensure you have permissions to read the files and write the temporary
diff.txtin the script's directory.
-