I need to write a batch or command to accomplish:
Scenario: There are about 100 odd folders in a parent directory which conatain a file "report.xml". I need to find these files and copy all the 40-50 files found to some seperate directory. Since all the files have the same name "report.xml", I need to rename the files with a name identifying the location they were found i.e. their parent folder. So if the file is found in a sub folder SB, it will be called as SB.xml.C:\Reports\report\SERVER1\folder\report.xml -----> SERVER1.xml
C:\Reports\report\SERVER2\folder\report.xml -----> SERVER2.xml
C:\Reports\report\SERVER3\\folder\report.xml -----> SERVER3.xmlI know a for loop will do the trick, but how to tokenize the full file path and accomplish it?
Appreciate your time..
Thanks to Razor2.3 for showing how to get the parent folder. ==================================================
@echo off & setLocal EnableDELAYedeXpansionfor /f "tokens=* delims= " %%a in ('dir/b/s/a-d c:\files\*.doc') do (
set P=%%~Pa
set P=!P:~0,-1!
call :sub1 !P!
echo.copy "%%a" "d:\dest\!F!%%~Xa"
)goto :eof
:sub1
set F=%~N1
goto :eof
=====================================
Helping others achieve escape felicityM2
You don't have to thank me; just knowing it's useful is enough. Also, I've refined that trick a bit, because I apparently hate sub-functions. @echo off & setLocal EnableDELAYedeXpansion for /f "tokens=* delims= " %%a in ('dir/b/s/a-d c:\files\*.doc') do ( for %%p in ("%%~Pa.") do echo.copy "%%a" "d:\dest\%%~Np%%~Xa" )
Hi R2, Yeah, subs are not optimal.
A couple days ago I was working one with nested FORs and got so lost I forgot what I started out to do.
LOL
=====================================
Helping others achieve escape felicityM2
Thanks a ton to R2 and M2...you guys are genius...the script is working fine.
Can I get more higher parent levels rather than the immediate parent of a file which this script does?C:\Reports\report\SERVER3\\folder\report.xml -----> SERVER3.xml
So in this case I dont want the new file to be folder.xml, rather SERVER3.xml which is a level above the imediate parent of the file...I actually want to go to the 3rd parent of the file..:)
So in this path which folder do you want? C:\Reports\report\SERVER3\folder
=====================================
Helping others achieve escape felicityM2
I will want to have "report" in the following path C:\Reports\report\SERVER3\folder
@echo off & setLocal EnableDELAYedeXpansion for /f "tokens=* delims= " %%a in ('dir/b/s/a-d e:\bak\*.doc') do (
for /f "tokens=2 delims=\" %%f in ("%%~Pa") do (
echo copy "%%a" "d:\dest\%%f%%~Xa"
)
)
=====================================
Helping others achieve escape felicityM2
If you want to "go up" one more level, just replace "%%~Pa." with "%%~Pa.." And if you want to just rename, just replace copy "%%a" "d:\dest\%%~Np%%~Xa" with ren "%%a" "%%~Np%%~Xa"
Yes (14) | ![]() | |
No (14) | ![]() | |
I don't know (15) | ![]() |