Comparing two files in batch script -


i trying compare 2 files in manner, each line of file 1 compared every line of file 2 , if no match found, write line seperate file.

below code wrote not working expected,

@echo on cd path /f %%a in (file1.txt) ( /f %%b in (file2.txt) ( if %%a==%%b ( echo lines same ) else ( echo %%a >> file3.txt ) ) ) 

i getting error saying, syntax of command incorrect. please me this.

the findstr method foxidrive shows fastest pure batch way approach problem, if file2 large. however, there number of scenarios can cause fail: regex meta-charactes in file 1, quotes and/or backslashes in file 1, etc. see what undocumented features , limitations of windows findstr command? of potential issues. bit more work can make solution more reliable.

  • the search should explicitly made literal
  • the search should exact match (entire line)
  • any backslash in search line should escaped \\
  • each search should stored in temp file , \g:file option used

also, don't describe format of each line. /f statements read first word of each line because of the default delims option of <tab> , <space>. suspect want set delims nothing. want disable eol option lines beginning ; not skipped. requires weird looking syntax. added usebackq option in case ever deal file names must quoted.

@echo off setlocal disabledelayedexpansion set "file1=file1.txt" set "file2=file2.txt" set "file3=file3.txt" set "search=%temp%\search.txt"  >"%file3%" (   /f usebackq^ delims^=^ eol^= %%a in ("%file1%") if "%%a" neq "" (     set "ln=%%a"     setlocal enabledelayedexpansion     (echo(!ln:\=\\!) >"%search%"     findstr /lxg:"%search%" "%file2%" >nul || (echo(!ln!)     endlocal   ) ) del "%search%" 2>nul 

there extremely fast 1 line solution if file2 not contain \" , can afford case insensitive search: reverse findstr search lines in file1 don't exist in file 2. search must case insensitive because of why doesn't findstr example multiple literal search strings find match?.

findstr /livxg:"file2.txt" "file1.txt" >"file3.txt" 

this not work if file2 contains \" because of escape issues. preprocess file2 , escape \, might use first solution if restricting pure batch solution.

if willing use hybrid jscript/batch utility called repl.bat, have extremely simple , efficient solution. repl.bat performs regex search , replace operation on each line of stdin, , writes result stdout.

assuming repl.bat in current directory, or better yet, somewhere within path:

@echo off setlocal set "file1=file1.txt" set "file2=file2.txt" set "file3=file3.txt" set "search=%temp%\search.txt"  type "%file2%"|repl \\ \\ >"%search%" findstr /livxg:"%search%" "%file1%" >"%file3%" del "%search%" 2>nul 

note solution still must perform case insensitive comparison.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -