When you define a literal string in a batch file, like set "Text=A single %%-sign"
or echo A single %%-sign
, you always have to manual double %
-signs; otherwise, the %
-expansion phase consumes them and tries to expand variables (refer to this answer for more details).
However, when the input text comes from somewhere else, like user input (set /P Text="Enter text: "
) or from a file (e. g., read by for /F
) you do not have to manually double %
-signs, because the %
-expansion phase is already completed when the text arrives.
This is the original answer before I recognised the real problem:
Well, the following line in your code cannot work:
set "Text=%Text:^%=%%%"
Because, besides the fact that it would actually replace ^%
rather than %
, the %
-sign behind the =
-sign finishes this sub-string substitution expression, and the remaining %%
become then replaced by a single literal %
(refer to this answer for more details).
To double %
-signs in an arbitrary string you need to enable delayed expansion, because this uses !
instead of %
to mark variables, which do not interfere with the literal %
-signs you want to replace/double:
@echo off
rem /* You have to double `%`-signs when you put a literal string here; so
rem this literaly sets `https://www.google.com/search?q=%clipboard%`: */
set "Text=https://www.google.com/search?q=%%clipboard%%"
rem // Enable delayed expansion:
setlocal EnableDelayedExpansion
rem // Literal `%`-signs still have to be doubled here:
set "Text=!Text:%%=%%%%!"
rem // Return the string with `%`-signs doubled:
echo Delayed expansion: !Text!
echo Normal expansion: %Text%
set Text & rem // (avoiding `echo` here to review the true variable value)
rem // Variables set/changed since `setlocal` become lost past this point:
endlocal