0

Using batch commands how do I get the folder path/directory from a string?

For example, if I have the string "C:\user\blah\abc.txt" how do I split the string so I can just get the folder part, ie, "C:\user\blah\"?

If pass the string "C:\user\blah\abc.txt" in the command line of a batch file, how do I split that string into just the folder part?

REM // Grab "C:\user\blah\abc.txt" from the command line
SET path="%*" 
REM // The following doesn't successfully capture the "C:\user\blah\" part
SET justFolder=%path:~dp1%
sazr
  • 24,984
  • 66
  • 194
  • 362
  • This question has already been asked; see http://stackoverflow.com/questions/636381/what-is-the-best-way-to-do-a-substring-in-a-batch-file – Riking May 10 '12 at 04:45
  • @Riking Thats for the current working directory, ie, the path where the batch file resides. My question is about obtaining the folders from a string/path(which is not the current working directory) – sazr May 10 '12 at 04:50

2 Answers2

1

the ~dp option only works with the batch parameters (%1 %2 ...) or with FOR substitution parameters (%%a %%b ...). Read HELP CALL.

So, to achieve what you want, try the following code

call :setJustFolder "%*"
echo %justFolder%
goto :eof

:setJustFolder
set justFolder=%~dp1
goto :eof

As an aside note, my personal preference is not to add " around user entered filenames. I would code the previous code simply as

set justFolder=%~dp1
echo %justFolder%
PA.
  • 28,486
  • 9
  • 71
  • 95
1

If you want to get the path from a string or from the current working directory is nearly the same.

set "myPath=%~dp1"
echo %myPath%

Or if you want to get it from a variable you could use FOR/F.

set myPath=C:\windows\xyz.txt
for /F "delims=" %%A in ("%myPath%") do echo %%~dpA
jeb
  • 78,592
  • 17
  • 171
  • 225