Search code examples
javabatch-filecommand-linesystem-variabledelayedvariableexpansion

How to find and replace a string in %PATH% system variable with variables in a batch file?


I am trying to upgrade Java with a batch file, and I need to change the PATH system variable to reflect that change. At the beginning of the PATH variable I have

C:\Program Files\Java\jdk1.8.0_51;...

I need to change the jdk value to be jdk1.8.0_60. I'm relatively new to command line and batch files, and so I may be misunderstanding something. Here is what I am trying.

I have a couple variables

jVersion=1.8.0_
javaPath=C:\Program Files\Java
newVersion=60
oldVersion=51

I found something about replacing strings with literal values like so

set PATH=%PATH:1.8.0_51=1.8.0_60%

but I can't get it to work with variables...

set PATH=%%PATH:%jVersion%%oldVersion%=%jVersion%%newVersion%%%

I don't know if you need 2 %'s around the outside, or just one, or !'s. I'm not super confident in my knowledge of delayed expansion. I also don't know if this is possible.

As a bonus, I would really like to be able to take whatever comes after ...\Java\ and replace it with my new value. This would be just in case I don't know the value in the PATH variable for the jdk

Thanks!

EDIT: By using the command call before a modified version of my code I was able to get it to work

call set PATH=%PATH:%jVersion%%oldVersion%=%jVersion%%newVersion%%

I'm still trying to figure out how to make it generic and change whatever comes after ...\jdk to the values I have.


Solution

  • paste the Below Code in a bat file and that should solve the problem

    @echo off
    
    setlocal EnableDelayedExpansion
    set jVersion=1.8.0_
    set "javaPath=C:\Program Files\Java"
    set newVersion=60
    set oldVersion=51
    set PATH=%jVersion%%oldVersion%
    echo before path change : !PATH!
    set PATH=!PATH:%jVersion%%oldVersion%=%jVersion%%newVersion%!
    echo final path change  : !PATH!
    pause