Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch replace with special characters not working

Tags:

batch-file

cmd

I'm trying to d a simple batch replace of doublequotes to singlequotes. The teststring must containg special characters, at most: "<LF>" I cannot replace the double quotes there, as the batch just exists with Syntaxerror. Do you know why, or how to overcome this?

SET TEST="<LF>","<HT>"
SET modified=%TEST:"='%  <-- Syntaxerror
ECHO %modified%
like image 683
membersound Avatar asked Jul 04 '26 19:07

membersound


2 Answers

Use delayed expansion:

setlocal enabledelayedexpansion
SET TEST="<LF>","<HT>"
SET modified=!TEST:"='!  <-- Syntaxerror
ECHO !modified!

As Mr Fuzzy Button notes, the problem is that the shell interprets < and > as redirection. Delayed expansion (using ! instead of %) expands variables after parsing and thus does not affect redirection.

You can solve the SET without delayed expansion by enclosing the argument in quotes:

SET "modified=!TEST:"='!"

But the ECHO would still be problematic, then.

like image 199
Joey Avatar answered Jul 07 '26 15:07

Joey


While delayed expansion is a good thing, it's not necessary to answer this question. There are also times when setlocal isn't available. I ran into one.

In the windows shell, string matching for quotes works on outermost match pairs (in most cases, but not all), not innermost.

SET TEST="<LF>","<HT>"
echo %TEST%
SET "modified=%TEST:"='%"
echo.|set /p "___=%modified%"

Workaround: If echo can't print something, set can. Go figure.

like image 26
TylerY86 Avatar answered Jul 07 '26 14:07

TylerY86



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!