0

I would like some help in improving on the answer in this question:

Remove unwanted path name from %path% variable via batch

I have the following path:

PATH=C:\Program Files\Java\jre1.8.0_141\bin;C:\windows\system32;C:\windows;...

The first part was set via variable:

JAVA_HOME=C:\Program Files\Java\jre1.8.0_141
PATH=%JAVA_HOME%\bin;C:\windows\system32;C:\windows;

While I know the following will work, I would prefer to use the variable JAVA_HOME, this way as JAVA_HOME changes the script does not! How would I take the following and modify it to use the %JAVA_HOME% variable?

Rather than %PATH:C:\Program Files\Java\jre1.8.0_141\bin;=%

I would like something like the following, but the notation eludes me.

%PATH:%%JAVA_HOME%%\bin;=%
Sam Carleton
  • 1,339
  • 7
  • 23
  • 45

1 Answers1

1

I can understand that the notation is somewhat strange with all the percentage signs.

I made up this little thing to show something that might make it easier to see what happens:

@echo off
setlocal EnableDelayedExpansion

set something=fobaaaao
set toRemove=baaaa

echo %something%

set result=!something:%toRemove%=!

echo %result%

I chose some other values than my path variable but the idea remains the same. You can modify the variables to add something like \bin as in your case for example.
Here you can see that from what would have ended up as %something:%%toRemove%%=% !something:%toRemove%=! came up.

The syntax is still the same <marker>variableName:> marker>toReplace</marker>=replacingWith</marker>
But now we are using other markers: ! instead of % and % instead of %%.

How does this work and why?

There is an important line at the top of the little example: setlocal EnableDelayedExpansion which enables the exclamation mark to be used as variable "marker". The difference to the percentage sign is that the variable in exclamation marks will be evaluated at runtime whereas the other one is already at "compile-time" (which does not really exist in batch, but hopefully it is clear what I mean; suggestions for this welcome :) ).

So the statement !something:%toRemove%=! will at runtime already look like: !something:baaaa=! and only the last part has to be done which is the replacement. So in short: We are using DelayedExpansion to make sure the replacement is happening after evaluating the string to replace.

Other than that there might not be an easier way to replace/remove something entirely from a variable in batch.

Sure you can go over it splitting by ; and check if the value is the one you want to have sort it out, add everything else up to a pile and set that as new path but the above would make it the most readable I would say.

Community
  • 1
  • 1
geisterfurz007
  • 5,292
  • 5
  • 33
  • 54