I wrote a batch script which I want it to look into folders and find textfiles which match a certain pattern. When there is a match with the pattern that i specified, i want to create a folder and move the matched files into the created folder.
@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)
)
Folder_Name.txt
Folder_1
Folder_2
Folder_3
The script will go into the sub directories of each folder, eg.(C:\Users\halo\Desktop\Scripts\Move\folder_1\logs) and find files which match the date pattern of the previous month,yyyymm eg.(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 doesnt 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. Thanks for help.
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.