anallyexcel anallyexcel - 8 months ago 101
Bash Question

Batch file to find multiple string using findstr and copy files to a folder

I am attempting to find multiple strings in files in a directory, there are thousands. I currently run the following command to search the directory:

findstr /s "customerid" *

Now this allows me to find the file that contains that string. I normally have two pieces of information a customer id and an event type. One customer can have up to 30 associated event such as "website registration".

What I would like to do is, search the directory for both the customer id and the event. Then copy the file to a new location. Is this possible in a batch file?


Supposing you want to find all files that contain both words (customer and event in this example), you could use the following script:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "PATTERN=*.txt"
set "SOURCE=."
set "TARGET=D:\Data"
set "STRING1=customer"
set "STRING2=event"

pushd "%SOURCE%" && (
    for /F "delims=" %%F in ('findstr /S /M /I /R /C:"\<%STRING1%\>" "%PATTERN%"') do (
        for /F "delims=" %%E in ('findstr /M /I /R /C:"\<%STRING2%\>" "%%F"') do (
            ECHO copy "%%E" "%TARGET%\%%~nxE"

exit /B

After having tested the script, remove the upper-case ECHO in front of the copy command!