I have a file name with fullpath and want to get the filename and the parent directory of the file.How can I parse this in batchscript?

e.g for /f "tokens=4,5 delims=\" %%a in ("F:\mydata\WebLogs\MyServerName001\u_ex100206.log")

in the above line token 4 is the servername and 5 is the filename.But this will not be always 4 and 5.So how can I get the last two tokens in a batch script?because in my scenario the filename will be the last token and the server name will be the token before that.

link|improve this question
feedback

2 Answers

up vote 0 down vote accepted

Use %~nxI for the filename and use the code from the selected answer in this stackoverflow post for the parent folder.

link|improve this answer
feedback

The post pointed to by Helvick is over the top. Here is a simple way to get the parent dir (or the parent's parent dir, etc):

for /D %%I in ("F:\mydata\WebLogs\MyServerName001\u_ex100206.log") do (
   echo filename=[%%~nxI]
)
for /D %%I in ("F:\mydata\WebLogs\MyServerName001\u_ex100206.log\..") do (
   echo parent dir=[%%~nxI]
)
for /D %%I in ("F:\mydata\WebLogs\MyServerName001\u_ex100206.log\..\..") do (
   echo parent's parent dir=[%%~nxI]
)

... etc. The file does not need to exist.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.