Reputation: 231
I want to rename files in a directory based on the name of containing directory, like
c:\bin\data01\foo.txt
to
c:\bin\data01\data01.txt
following the post How to get folder path from file path with CMD .
Upvotes: 0
Views: 2263
Reputation: 846
If you only need the parent directory name you can use something like the folowing which works for a maximum nesting level of 10.
ECHO %~p0>path.txt
FOR /F "tokens=1,2,3,4,5,6,7,8,9,10 delims=\" %%G in (path.txt) DO (
IF NOT [%%G]==[] SET myVar=%%G
IF NOT [%%H]==[] SET myVar=%%H
IF NOT [%%I]==[] SET myVar=%%I
IF NOT [%%J]==[] SET myVar=%%J
IF NOT [%%K]==[] SET myVar=%%K
IF NOT [%%L]==[] SET myVar=%%L
IF NOT [%%M]==[] SET myVar=%%M
IF NOT [%%N]==[] SET myVar=%%N
IF NOT [%%O]==[] SET myVar=%%O
IF NOT [%%P]==[] SET myVar=%%P
)
DEL path.txt /F /Q
ECHO %myVar%
Based on Fraser Graham's answer
Upvotes: 0
Reputation: 4820
Microsoft has a good Batch Reference that explains how you can do a for loop to tokenize a file path and pull out the directory name...
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/batch.mspx?mfr=true
If you have a file that contains a list of files, tmp.txt...
c:\temp\folder\foo.txt
you can parse those filenames in batch with...
for /F "delims=\ tokens=1,2,3" %%i in (tmp.txt) do call echo %%i %%k %%j
and that produces...
%%i = c:
%%j = temp
%%k = folder
after that you can use the variable that matches the directory name as the filename in your copy. However, this that only works if all the paths are the same depth.
Upvotes: 2