I have been reading great posts in this forum and got close to what I want to do but couldn't figure out the exact code.
I want to create a windows batch file to do following:
- Perform a looped search for each line item of a text file (this is a list of keyword) to locate f开发者_如何转开发iles in a a specific directory
- For this search partial match is okay.
- Each time a file is found, move it to a predefined directory (e.g. C:\temp\search_results)
Thanks.
I'm not running Windows at the moment, so I can only post some ideas, not the solution.
1) Use for /f
to iterate over file contents.
2) Use find "%Keyword%" %SourceDir%
to get the list of matching files. You will have to parse out file names from the output of find
.
2a) As an alternative, you can iterate over files in the source dir (with nested for
) and call find
for each file, discarding its output and using its exit code (%ERRORLEVEL%
) to decide whether the file matches (it will return 0 if there is a match and nonzero if there is no match). Something like this:
for %%F in (%SourceDir%\*) do (
find "%Keyword%" %%F > nul
if not errorlevel 1 (echo File %%F matches) else (echo File %%F does not match)
)
3) Move matching files with move
.
There are multiple problems.
FIND /i "%A%" ... can't work, the name of the FOR-Varibale is %%A
And the second proble: With FIND you check the content of the file not the name.
And you should use indention to avoid too much parenthesis.
You better try
FOR /F "tokens=*" %%A IN (%listfile%) DO (
FOR %%f in (%searchdir%\*) do (
set "filename=%%~f"
set replaced=!filename:%%A=!
if !replaced! NEQ !filename! (
echo !filename! contains '%%A'
)
)
)
It tries to replace %%A inside of the filename with . If the replaced is not equal the filename, the filename must contain %%A
I wrote the following code but not sure if I am in the right track. Here is my setup: list.txt file contents are (my keywords for the filename search) --
one
two
five
ten
six
f1 folder contains --
four.txt
one.txt
three.txt
I want to move the matching ones to F2 folder, but the code simplicity I am using echo instead.
My code is:
@ECHO OFF
SETLOCAL EnableDelayedExpansion
SET listfile=D:\batchtest\list.txt
SET searchdir=D:\batchtest\f1
FOR /F "tokens=*" %%A IN (%listfile%) DO (
FOR %%f in (%searchdir%\*) do (FIND /i "%A%" %%f
if errorlevel 1 (
echo Search failed) else (
echo Search successful
)
)
)
)
It is running but not finding matching filenames.
Thanks.
精彩评论