Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

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.

share|improve this answer
    
you should at least clarify what %~nxl means, perhaps with an example and some output - its not necessarily obvious. I assume you actually mean %~nxa? –  jheriko Aug 21 '12 at 12:00

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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