Fuze
Fuze

Reputation: 423

How to expand environment variable inside string read from file?

I have a file with a list of paths. Some of them might include environment variables such as %USERPROFILE%.

Example:

%USERPROFILE%\dir
C:\another\dir

I'm then reading all the lines and concatenating with ; using this code (the cat and tr commands are available because of git):

set include_file=C:\path\to\file.txt
for /f "delims=" %%i in ('cat %include_file% ^| tr "\\n" ";"') do set include_content=%%i

This creates a variable with the string %USERPROFILE%\dir;C:\another\dir Normally running echo %USERPROFILE% would give you something like C:\Users\xxx\dir but running it with %include_content% just outputs the original string without expanding %USERPATH%

My final plan is to add the directories to my PATH like this set PATH=%include_content%;%PATH% but this doesn't work since the variable isn't expanded.

My question is can I somehow expand the variables in the string so that the real directories get added to the path?

Upvotes: 1

Views: 1519

Answers (2)

rojo
rojo

Reputation: 24466

Buliding on jeb's answer, you may wish to prevent the same directory from being added to %PATH% multiple times. To do this, loop through each directory both in %PATH% and in %include_content%.

@echo off
setlocal enabledelayedexpansion

set include_file=test.txt
for /f "delims=" %%i in ('cat %include_file% ^| tr "\n" ";"') do set "include_content=%%i"

call set "include_content=%include_content%"

for %%I in ("%include_content:;=" "%") do if exist "%%~I" (
    set found=
    for %%J in ("%PATH:;=" "%") do (
        if /I "%%~I"=="%%~J" set found=1
    )
    if not defined found set "PATH=!PATH!;%%~I"
)

:: uncomment to make permanent
rem setX PATH %PATH%
echo %PATH%

Upvotes: 2

jeb
jeb

Reputation: 82307

You can reparse a line by using CALL.

So this should do the job

call set "include_content=%include_content%"

After the for loop

Upvotes: 5

Related Questions