Home > Net >  Error in batch variable expansion with replacement containing parentheses
Error in batch variable expansion with replacement containing parentheses

Time:03-24

I have the following Batch script which replaces occurrences of {path} in a text file with a path:

@echo off
setlocal EnableDelayedExpansion

set path=C:\Program Files (x86)\foo

for /F "tokens=*" %%A in (template.txt) do (
    set line=%%A
    set line=!line:{path}=%path%!
    echo !line!
)

When I run this script I get the error message

\foo! was unexpected at this time.

If I remove the parentheses in the path it works as expected. How can I solve this problem? I cannot have quotes around the path in the text file so putting quotes around the path in the set statement is not an option.

CodePudding user response:

@echo off
setlocal EnableDelayedExpansion

set "mypath=C:\Program Files (x86)\foo"

for /F "tokens=*" %%A in (q71593680.txt) do (
    set "line=%%A"
    CALL :changeline
    echo !line!
)

FOR %%c IN ("%mypath%") DO for /F "tokens=*" %%A in (q71593680.txt) do (
    set "line=%%A"
    set "line=!line:{path}=%%~c!"
    echo !line!
)

GOTO :EOF

:changeline
set "line=!line:{path}=%mypath%!"
GOTO :eof

The problem is that the ) in the substitution-string is being taken as the closing parenthesis of the do.

Solution : make an internal subroutine as shown.

Use set "var1=data" for setting string values - this avoids problems caused by trailing spaces.

Don't use path as a variablename - it's a reserved word in batch, meaning the sequence in which the directories are searched to find an executable that isn't in the current directory.

CodePudding user response:

Use set path=%ProgramFiles(x86)%\foo first (this folder may be elsewhere, this variable is here to find it anyway), and surround the replacement set with quotes (see below).

Corrected program:

@echo off
setlocal EnableDelayedExpansion

set pathval=%ProgramFiles(x86)%\foo

for /F "tokens=*" %%A in (template.txt) do (
    set line=%%A
    REM Please note the quotes around the affectation. It avoids an interpretation.
    set "line=!line:{path}=%pathval%!"
    echo !line!
)

Side note: even with setlocal, avoid to name a variable path...

  • Related