I wrote a Batch script that searches through folders to find text files matching a certain pattern. When a match is found, I want to create a folder and move the matched files into it.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
set source=Folder_Name.txt
For /f "tokens=2-4 delims=/ " %%a in ('date /t') DO (set year=%%c)
For /f "tokens=2-4 delims=/ " %%a in ('date /t') DO (set /a month=%%b-1)
if !month! == 0 (set /a year=year-1)
if !month! == 0 (set month=12)
set exception=!year!!month!
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
::Check Every Folder in the source for pattern matching.
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FOR /f "tokens=* delims=" %%H IN (!source!) DO (
set location=%%H\Logs
For /R "!location!" %%f in ("*!exception!*.txt") Do (echo %%f>> output.txt)
)
This is an example text file Folder_Name.txt
:
Folder_1
Folder_2
Folder_3
The script will go into the subdirectories of each folder, e.g. C:\Users\halo\Desktop\Scripts\Move\folder_1\logs\
and find files which match the date pattern of the previous month yyyymm
e.g. 201511
.
So I hope to find files such as (cloud_20151101.txt
or cloud_20151102.txt
) and move them to a folder.
However, my script doesn't work when I read in the folder name. When I change the !location!
in the recursive for loop to C:\Users\halo\Desktop\Scripts\Move\folder_1\logs\
, it works.
I have not implemented moving the files as I want to resolve this issue first.
First of all, check how you are getting the tokens for the dates. Since you are delimiting it at the "/" character, you will have 3 tokens from the date /t
command.
So for getting your date pattern, try doing like this:
For /f "tokens=3 delims=/ " %%a in ('date /t') DO (set year=%%a)
For /f "tokens=2 delims=/ " %%a in ('date /t') DO (set /a month=%%a-1)
Now for the checks in the directory read from "Folder_Name.txt", you could do:
FOR /f "tokens=* delims=" %%H IN (!source!) DO (
set location=%%H\Logs
dir /b !location! | findstr /r /c:"!exception!">>output.txt
)
Then you just need to implement the logic to move the files around. At the dir
line, you could output to something like:
dir /b !location! | findstr /r /c:"!exception!">>output_%%~nH.txt
So you will have one output file for each directory you read. The format of the output file will be: output_NAME-OF-THE-DIRECTORY-SEARCHED.txt
Hope it helps.