1

So I know how to do simple string replacing with the SET command.

Example:

set /p a=
set a=%a:<=^<%
echo %a%

(This example will change the prompted variable to the same thing but with the < character to be ^< to be be properly echoed if needed to)

I want to do the same thing but with the % character but I can't get it to work.

  • 1
    This could be a [XY-Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), probably you can solve your real problem without replacing anything. You should describe your problem, not your assumed solution – jeb Jan 06 '21 at 15:32
  • I edited my question to be more properly explained – Sean Armecin Jan 08 '21 at 04:35

3 Answers3

1
@ECHO OFF
SETLOCAL
SET "something=%%he%%llo%%"
ECHO %something%
ECHO ============
SETLOCAL ENABLEDELAYEDEXPANSION
SET "anotherthing=!something:%%=x!"
endlocal&SET "anotherthing=%anotherthing%"
ECHO %something%
ECHO %anotherthing%
GOTO :EOF

Like this, you mean?

Magoo
  • 68,705
  • 7
  • 55
  • 76
0

There was nothing wrong with your method, short of using doublequotes to protect from poison characters.

The main issue now, is in trying to see the content, because you'd be Echoing poison characters. To see it actually in place I included two methods, a Set command to list all variables beginning with a, (with a findstr thrown in to isolate only the one named a), and by using delayed expansion, which prevents the variable from being expanded when the command line is read/parsed. At the very bottom I included a method of showing it with the Echo command without using delayed expansion or doublequotes, as you can see to escape a caret, ^, you'll need in this case to use two more carets

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "a="
Set /P "a="
Set "a=%a:<=^<%"
Echo(%a%
Pause

(Set a) 2> NUL | %SystemRoot%\System32\findstr.exe /B /L /I "a="
Pause

SetLocal EnableDelayedExpansion
Echo(!a!
EndLocal
Pause

Echo(%a:^<=^^^<%
Pause
Compo
  • 30,301
  • 4
  • 20
  • 32
0

The full (known) rules for variable replacement can be found at SO: Percent Expansion Rules

In short: The search expression in a percent replacement expression can not start with a percent.
The search expression in a delayed replacement expression can not start with a exclamation mark.

But you can replace percent signs with delayed expression

setlocal EnableDelayedExpansion
set /p var=
set "var=!var:%%=REPLACE!"
echo(!var!

The percent sign itself has to be doubled here, because it collapse to a single percent in phase2 (percent expansion)

jeb
  • 70,992
  • 15
  • 159
  • 202