0

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.

Sen
  • 15
  • 1
  • 6

2 Answers2

2

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.

foo2
  • 21
  • 2
0

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

Helvick
  • 20,019
  • 4
  • 38
  • 55
  • 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