R – How to extract a full path from the PATH environment variable

batch-filecmdscriptingwindows

I want to extract a full path from the PATH environment variable with native cmd tools. Consider the following PATH content:

C:\Program Files\Windows Resource Kits\Tools\;C:\Perl\site\bin;C:\Perl\bin;C:\WI
NDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;c:\Program Files\Microsoft SQ
L Server\90\Tools\binn\;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Program Fi
les\Microsoft SQL Server\80\Tools\Binn\;C:\Program Files\Microsoft SQL Server\10
0\DTS\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\program fil
es\nmap\;C:\Program Files\WinRAR\;C:\Program Files\QuickTime\QTSystem\;C:\Progra
m Files\hydra-5.4-win\;C:\Program Files\john1701\run;C:\dig;;C:\cygwin;C:\wamp\b
in\mysql\mysql5.0.45\bin;C:\Program Files\MySQL\MySQL Server 5.0\bin;C:\Program
Files\Tail4win;C:\Program Files\Overlook Fing 1.1\bin

I want to extract only the following path:

C:\Program Files\MySQL\MySQL Server 5.0\bin;

Is FOR capable of such thing?

Best Answer

You can use for to tokenize at ; but you need to take care of paths that have a ; in them (and thus need quotes). All in all I'd say you'd build a pretty brittle solution with pretty much code at this point.

If you want to know where a certain executable is, then

for %%i in ("mysql.exe") do @echo.%%~$PATH:i

will tell you that (or not, if it's nowhere in the PATH).

UPDATE: Ok, I got it. One nasty little batch file follows:

@echo off
setlocal enabledelayedexpansion enableextensions
set p=%PATH%
:loop
for %%i in ("notepad.exe") do call :setvar "%%~$p:i"
if not :%x%:==:: (call :clearpath & goto loop)
goto :eof

:setvar
    set x=%~1
goto :eof

:clearpath
    echo %x%
    for %%x in ("!x!") do set d=%%~dpx
    set d=!d:~,-1!
    set p=!p:%d%=!
goto :eof

This will print all matching paths from PATH where notepad.exe was found (the first program I know off the top of my head to be in two places here). Adapt accordingly for your problem.

:clearpath simply deletes the found path from the variable and then we try matching again, until no match is left.

That said, this is still very un-pretty.