0

I have to search a particular folder having *.txt files, but the name of the file contains some dates like 20120712, 20120713 so on.

I would like to search for files having particular dates or greater and move them to another folder. How can I search for the filename containing a certain date or its greater using batch?

6
  • 1
    You could search for filenames with FOR...(*) or FOR /R and test then if it contains a date in your range Commented Jul 26, 2012 at 10:41
  • Side-note: please use punctuation in your future questions. Commented Jul 26, 2012 at 15:11
  • We need to know more about how the file names are formatted. If the filenames follow a particular template then it might not be too difficult. But if the date can be randomly embedded anywhere within the file name then it may be very difficult, perhaps impossible. Commented Jul 26, 2012 at 16:06
  • @dbenham the date can be extracted with Sed and passed for parsing. Shouldn't be that difficult... Commented Jul 26, 2012 at 16:16
  • @Eitan - A 3rd party Windows compatible version of sed definitely makes the task much simpler, though I generally try to stick with native batch capabilities. But the point I was making was that there might be multiple 7 char numeric strings within the filename. Without a good name template spec, there is no way to know which chars to extract. Commented Jul 26, 2012 at 17:37

1 Answer 1

1

Try something like:

@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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.