loopsbatch-filefindstr

Findstr in loop, batch file


I would like to ask you for a help. I have a text document colors.txt that contains many colors (hundreds of them, each on the separate line).

For example:

blue
white
yellow
green
magenta
cyan
white
black

Than I have folders, that contain subfolders and files. I have to make a script (batch file), that searches for colors thru all those folders, subfolders and files line by line. If specific color is used at least once, everything is OK. However, if some colour is completely unused (can not be found) in any of these folders, subfolders and files, I have to know which color it is.

It is possible to do it manually and test all the colors with command such this one:

findstr /s/m "blue" *.txt

But there are really hundreds of them and it would take too long.

Is there any possibility to do it through loop, with argument that varies according to lines in colors.txt?


Solution

  • This batch file can be used for this task:

    @echo off
    setlocal EnableExtensions DisableDelayedExpansion
    set "ColorsFolder=C:\Temp"
    set "SearchFolder=C:\Temp\Test"
    set "OutputFile=%ColorsFolder%\NotFoundColors.txt"
    
    rem Search for each color in colors.txt in all text files of the folder tree
    rem and output those colors not found in any text file into the output file.
    (for /F "usebackq delims=" %%I in ("%ColorsFolder%\colors.txt") do %SystemRoot%\System32\findstr.exe /I /M /R /S /C:"\<%%~I\>" "%SearchFolder%\*.txt" >nul || echo %%I)>"%OutputFile%"
    
    rem Delete output file on being empty if all colors were found.
    for %%I in ("%OutputFile%") do if %%~zI == 0 del "%OutputFile%"
    endlocal
    

    The only needed command line is the for command line which could be executed also from a Windows command prompt window with:

    (for /F "usebackq delims=" %I in ("C:\Temp\colors.txt") do %SystemRoot%\System32\findstr.exe /I /M /R /S /C:"\<%~I\>" "C:\Temp\Test\*.txt" >nul || echo %I)>"C:\Temp\NotFoundColors.txt"
    

    The output file C:\Temp\NotFoundColors.txt is empty if all colors were found at least once in a *.txt file in directory C:\Temp\Test and its subdirectories. The batch file above deletes the output file if being empty.

    The text file with the colors must not be stored in directory searched by findstr or must have a different file extension.

    To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.

    See also: