Batch file to pull last folder name from a unc path for a specific file

I want to create a batch file that can read through a file containing a list of files

the files are in the format of


The folder depth is variable

I want to write a batch file that will find FolderN for each filepath listed in fileX.txt
Who is Participating?
Shift-3Connect With a Mentor Commented:
This runs slow but should handle directories of any depth.

@echo off
setlocal enabledelayedexpansion
set list=fileX.txt
for /F "tokens=* usebackq" %%G in ("%list%") do (
 set parent=%%~dpG
 for /F "tokens=*" %%H in ("!parent:~0,-1!") do echo %%~nH

Open in new window

Steve KnightIT ConsultancyCommented:
Unless I'm going mad I'm sure I saw an answer from sirbounty here a second ago?!
Perhaps you just need more sleep... :^)
I read the Q wrong and as such had my comment removed.  Besides, I remembered you've got the helm at this time of day...haha!
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Steve KnightConnect With a Mentor IT ConsultancyCommented:
Try this.  Handles upto 10 deep directories at the moment, needs some
@echo off

for /f "delims=\ tokens=1-10" %%a in (fileX.txt) do call :process "%%a" "%%b" "%%c" "%%d" "%%e" "%%f" "%%g" "%%h" "%%i" "%%j"
goto :eof

set prevfolder=
set lastfolder=

if "%~1"=="" goto foundit
 set prevfolder=%lastfolder%
 set lastfolder=%~1
goto :next
 if "%prevfolder%"=="" set prevfolder=%lastfolder%
 echo Folder is %prevfolder%

Steve KnightIT ConsultancyCommented:
Powers of being able to get such things done eh!  I wasn't going mad then!

sollusAuthor Commented:
Great, thanks for the answers. They both work, but I found Shift-3's answer to be more complete.

If you have the time I would appreciate if you could explain the working of the code.

Specifically how are these instructions interpreted
%%G represents each line in the text file.  %%~dpG is the disk (in this case just \\) and path from each of these lines. !parent:~0,-1! removes the last character (a trailing backslash) from this path.  %%~nH is the last folder in the path.

See these pages for more information:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.