Guna
Guna

Reputation: 141

Manipulation on delayed expansion string variable is failing

I am trying to find a particular line from an XML file and extract the value using string manipulation operations.

Below is the code I am trying.

@echo off
setlocal enabledelayedexpansion

::Expected line is "<filename>c:\temp\file1</filename>"

for /f "tokens=*" %%i in ('findstr /i "filename" file1.props') do (
    SET LINE=%%i
)

echo !LINE!

SET FILENAME=!LINE:<filename>=!
SET FILENAME=%FILENAME:</filename>=%
ECHO !FILENAME!

And the output is:

<filename>c:\temp\file1</filename>
The system cannot find the file specified.
ECHO is off.

I actually want this value c:\temp\file1

Someone please help me correct the code or please suggest any other simpler way.

Upvotes: 0

Views: 149

Answers (1)

Stephan
Stephan

Reputation: 56165

The problem is the execution of set. The parser interprets the > and < as redirection, so it will fail with a syntax error. Use quotes to process it as intended (`set "var=value"):

@echo off
setlocal enabledelayedexpansion
REM echo ^<filename^>c:\temp\file1^</filename^>>file1.props

::Expected line is "<filename>c:\temp\file1</filename>"

for /f "tokens=*" %%i in ('findstr /i "filename" file1.props') do (
    SET "LINE=%%i"
)

echo !LINE!

SET "FILENAME=!LINE:<filename>=!"
SET "FILENAME=%FILENAME:</filename>=%"
ECHO !FILENAME!

Output is:

<filename>c:\temp\file1</filename>
c:\temp\file1

Upvotes: 2

Related Questions