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"
)
)
popd
)
endlocal
exit /B
After having tested the script, remove the upper-case ECHO
in front of the copy
command!
@echo off
setlocal enableextensions disabledelayedexpansion
set "sourceFolder=x:\somewhere"
set "targetFolder=y:\another\place"
set "customerID=00000000"
set "event=eeeeeeeeee"
for /f "delims=" %%a in ('
findstr /m /s /l /c:"%customerID%" "%sourceFolder%\*"
^| findstr /f:/ /m /l /c:"%event%"
') do (
ECHO copy "%%~fa" "%targetFolder%"
)
findstr
can deal with it. We only need two instances
- The first one will search all the input files for the first string, returning only the list of matching files. This list of files will be piped into the second instance
- The second one will search the second string but only in the files found by the first instance, reading the list of files where to search from standard input stream (
/f:/
)
The rest of the code is just a for /f
wrapping the two findstr
commands to process the output of the second one and do the file copy.
After having tested the script, remove the upper-case ECHO
in front of the copy
command!