2

In a CMD batch file, it's easy to extract the path/folder name for an argument:

set folder=%~f0
set dirname=%~p0

It's described in help call and help for. Now how do I do the same with a path stored in a variable? The following doesn't work:

set VAR="c:\Program Files (x86)\Java\jdk1.6.0_29\bin\java.exe"
echo %~pVAR%

The alternative I found is to use either FOR or CALL:

for %%A in (%VAR%) do set P=%%~pA
for %%A in (%VAR%) do set N=%%~nA
for %%A in (%VAR%) do set E=%%~xA

and then use %P% (c:\path), %N% (appname), %E% (.exe) as I need.

For example, I recently needed to convert a java.exe variable to map to javaw.exe instead, so I end up writing this:

if %java_exe%=java (
    set javaw_exe=javaw
) else (
    for %%a in (%java_exe%) do set p=%%~pa
    for %%a in (%java_exe%) do set n=%%~na
    for %%a in (%java_exe%) do set x=%%~xa
    set n=%n:java=javaw%
    set javaw_exe=%p%%n%%x%
)
if not exist %javaw_exe% set javaw_exe=%java_exe%

Can someone shine in with a better solution that doesn't look totally hackish?

2 Answers 2

2

There is no other way to do what you need. The only improvement in your code is that several values may be taken in the same for, and the elimination of one line:

if %java_exe%=java (
    set javaw_exe=javaw
) else (
    for %%a in (%java_exe%) do set p=%%~pa& set n=%%~na& set x=%%~xa
    set javaw_exe=%p%%n:java=javaw%%x%
)
if not exist %javaw_exe% set javaw_exe=%java_exe%
Sign up to request clarification or add additional context in comments.

Comments

0
@echo off

:: go the run dir
cd %~dp0
:: this is the dir containing the batch file
set MyDir=%CD%

for %%A in (%0) do set MyDriveLetter=%%~dA
for %%A in (%0) do set MyPath=%%~pA
for %%A in (%0) do set MyName=%%~nA
for %%A in (%0) do set MyExtension=%%~xA

ECHO MYNAME IS %0
echo MyDriveLetter is %MyDriveLetter%
echo MyPath is %MyPath%
echo MyName is %MyName%
echo MyExtension is %MyExtension%

PAUSE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.