Search code examples
batch-filecmdcomparefindstr

Windows Command | Split A File to Contain and Doesn't Contain By Other File


I have 2 files: tempfile.txt & mainfile.txt. I would like to parse tempfile and check whether the strings in it exists in mainfile. If they do, I would like to put the string in contain.txt. If not, they should be placed in dcontain.txt

When I run the script below, dcontain.txt file does not get created. Instead, all the search strings end up in contain.txt.

@echo off
for /f "tokens=1" %%a in (tempfile.txt) do (
findstr /m "%%a" mainfile.txt
if %errorlevel%==0 (
echo %%a>>contain.txt
)else (
echo %%a>>dcontain.txt
)
)

Please see below the contents of mainfile, tempfile and what should contain.txt and dcontain.txt should include. The last column is what I see instead.

mainfile  tempfile   contain   dcontain |O|contain.txt
11111     11111      11111     aaaaa    |U|11111 
22222     aaaaa      22222     bbbbb    |T|aaaaa       
33333     22222      33333              |O|22222   
44444     bbbbb                         |U|bbbbb      
55555     33333                         |T|33333                        

Solution

  • Batch is a finicky beast and there are a couple of subtle problems with the way you are doing this. %ERRORLEVEL% expansion happens at parse time within DO block, so it is evaluated only once and you do not get 0 and 1 as you would expect.

    Setting enabledelayedexpansion helps with that. When you are checking for equality, EQU and NEQ are the "numeric" operators, while == would be used for string comparison.

    You can make your code work if you change it as follows:

    @echo off
    setlocal enabledelayedexpansion
    for /f "tokens=1" %%a in (tempfile.txt) do (
    findstr /I "%%a" mainfile.txt >nul 2>&1
    
    if ERRORLEVEL 1 (
    
        echo %%a>>dcontain.txt  
    
    )else (
    
        echo %%a>>contain.txt   
    )
    )