luanoob
luanoob

Reputation: 349

Batch : getting the last folder name from a absolute path

I am using a Batch script to automatically backup files to my NAS and I need to get the last folder name from an absolute path, like from "C:\Things\Folder" to "Folder"

Upvotes: 2

Views: 4634

Answers (3)

David
David

Reputation: 21

To not have any issue with space, I propose this code:

Set NasPath=C:\Things\My Space\Folder
Set GetFolderTemp=%NasPath%
:GetFolder
FOR /F "tokens=1,* delims=\" %%1 IN ("%GetFolderTemp%") do (
set NasFolder=%%1
set GetFolderTemp=%%2
)
if not "a%GetFolderTemp%"=="a" goto :GetFolder

echo %NasFolder%

Upvotes: 2

Bo Real
Bo Real

Reputation: 136

Assuming C:\Program Files\Mickey\Mouse-like paths (without quotes), you could also use the following code:

setlocal EnableDelayedExpansion

set path=C:\Program Files\Microsoft\Mickey\Mouse
:shift
for /f "tokens=1* delims=\/" %%i in ( "!path!" ) do (
    set folder=%%i
    set path=%%j
)
if not [!path!] == [] goto :shift

echo folder: !folder!

endlocal

Upvotes: 0

Hand-E-Food
Hand-E-Food

Reputation: 12814

It's a bit of a hack, but you can use:

Set NasPath=C:\Things\Folder
Set NasFolder=%NasPath%
:GetFolder
Set GetFolderTemp=%NasFolder:*\=%
If Not %GetFolderTemp%==%NasFolder% (
    Set NasFolder=%GetFolderTemp%
    Goto :GetFolder
)
Echo NasPath  =%NasPath%
Echo NasFolder=%NasFolder%
Exit /B

Whatever you do, don't put quotes around any part of the Set NasPath=... statement. Use quotes this way:

Set FromPath=C:\Program Files\Blah
Set NasPath=C:\Things\Folder
RoboCopy "%FromPath%" "%NasPath%"

Do not use quotes this way:

Set FromPath="C:\Program Files\Blah"
Set NasPath="C:\Things\Folder"
RoboCopy %FromPath% %NasPath%

Upvotes: 5

Related Questions