batch-filefindstr

Get conda environment path from env name


Hi I'm trying to get the path of a conda env from its name:

conda info --envs

I get:

base                     C:\ProgramData\Miniconda3
RPDA                  *  C:\ProgramData\Miniconda3\envs\RPDA
test310                  C:\ProgramData\Miniconda3\envs\test310
RPDA2                    C:\Users\u608771\.conda\envs\RPDA2

so if I do

conda info --envs | findstr /c:"RPDA"

I get:

RPDA                  *  C:\ProgramData\Miniconda3\envs\RPDA
RPDA2                    C:\Users\u608771\.conda\envs\RPDA2

how can i get just the path(neglecting the "*" if present)?: C:\ProgramData\Miniconda3\envs\RPDA

and how can i assign it to a variable, something like:

set envpath=conda info --envs | findstr /c:"RPDA"

Solution

  • I assume you are only interested in the item with the * and it appares only once in the request:

    As commandline:

    for /f "usebackq tokens=1,2,*" %a in (`conda info --envs ^| findstr /c:"*"`) do @set envpath=%c
    
    echo %envpath%
    

    In a batch script you have to double the %a => %%a

    @echo off
    for /f "usebackq tokens=1,2,*" %%a in (`conda info --envs ^| findstr /c:"*"`) do @set envpath=%%c
    

    Edit: As you opt to keep all lines for the pattern 'RPDA, here an extended solution that takes the names in the first column as part of the variable name:

    @echo off
    for /f "usebackq tokens=1,* delims= * " %%i in (
        `conda info --envs ^| findstr /b /c:"RPDA"`
    ) do @(
        set RESULT_%%i=%%j
    )
    

    To see the result type

    set "RESULT_"
    

    Edit: Evaluated some of user Mofi's suggestions and simplified the code.