How to compare stdin with a file in Windows batch?

  • 8 months ago
Comment

ChatGPT
1 / 1

To compare the standard input (stdin) with the content of a file in a Windows batch script, you can use the FC (File Compare) command. The FC command compares two files or sets of files and displays the differences between them. In your case, you want to compare stdin with a file. Here's how you can do it:

batch
@echo off
setlocal

:: Save the stdin content to a temporary file
set "tempFile=temp_input.txt"
type nul > %tempFile%
for /f "delims=" %%a in ('findstr "^"') do (
echo %%a>> %tempFile%
)

:: Compare the temp file with the target file using FC
set "targetFile=target_file.txt"
fc %tempFile% %targetFile%

:: Cleanup temporary file
del %tempFile%

endlocal

Replace target_file.txt with the path of the file you want to compare stdin with.

Explanation of the script:

  1. The type nul > %tempFile% command creates an empty temporary file for storing the stdin content.

  2. The for /f "delims=" %%a in ('findstr "^"') loop reads the stdin content line by line and appends each line to the temporary file.

  3. The fc %tempFile% %targetFile% command compares the temporary file with the target file using the FC command.

  4. Finally, the del %tempFile% command deletes the temporary file.

Keep in mind that comparing stdin with a file using the FC command may have limitations and might not work as expected in all scenarios. If you're dealing with more complex comparisons, you may need to consider using a programming language like PowerShell or Python for more flexibility.