如何在批处理文件编程中搜索文件名中的特定字符串?

时间:2012-07-26 09:05:16

标签: windows batch-file

我必须搜索包含*.txt个文件的特定文件夹,但该文件的名称包含一些日期,例如2012071220120713等等。

我想搜索具有特定日期或更长日期的文件,并将它们移动到另一个文件夹。如何使用批处理搜索包含特定日期或更大日期的文件名?

1 个答案:

答案 0 :(得分:1)

尝试类似:

@echo off

setlocal

set SEARCH_DIR=c:\temp\source
set TARGET_DIR=c:\temp\target
set DATE_THRESHOLD=20120720

REM ***
REM *** NEED TO MODIFY REGEX ACCORDINGLY (THIS REGEX EXPECTS THE FILES TO BE CALLED YYYYMMDD.TXT).
REM ***
for /f %%F in ('dir /b %SEARCH_DIR%\*.txt 2^>nul ^| %SystemRoot%\System32\findstr.exe /r /c:"^[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\.txt"') do (
    call :PROCESS_FILE "%%F"
    )

endlocal

goto END


:PROCESS_FILE

set PF_FILENAME=%1
set PF_FILENAME=%PF_FILENAME:"=%

REM ***
REM *** EXTRACT THE NUMERIC PART FROM THE FILENAME.  THIS WILL NEED MODIFYING IF YOUR FILENAME FORMAT IS NOT YYYYMMDD.TXT.
REM ***
set /a PF_YYYYMMDD=%PF_FILENAME:~0,8%

echo Processing file [%PF_FILENAME%]...

REM ***
REM *** CHECK DATE.
REM ***
if %PF_YYYYMMDD% LEQ %DATE_THRESHOLD% (
    echo File not old enough - skipping.
    goto END
    )

REM ***
REM *** MOVE FILE.
REM ***
echo Moving file....
move "%SEARCH_DIR%\%PF_FILENAME%" "%TARGET_DIR%"
if exist "%SEARCH_DIR%\%PF_FILENAME%" (
    echo ERROR : Failed to move file.
) else (
    echo File moved successfully.
)

goto END


:END