Reputation: 23
How to replace the string 1234567890
by !@#$%^&*()
in Windows batch file?
set temp_mm=1234567890
echo befor:%temp_mm%
set temp_mm=%temp_mm:1=!%
set temp_mm=%temp_mm:2=@%
set temp_mm=%temp_mm:3=#%
set temp_mm=%temp_mm:4=$%
set temp_mm=%temp_mm:5=^%%
set temp_mm=%temp_mm:6=^^%
set temp_mm=%temp_mm:7=^&%
set temp_mm=%temp_mm:8=^*%
set temp_mm=%temp_mm:9=^(%
set temp_mm=%temp_mm:0=^)%
echo after:%temp_mm%
Upvotes: 2
Views: 241
Reputation: 80203
@ECHO Off
SETLOCAL
set temp_mm=12345678901234567890
echo befor:%temp_mm%
set "temp_mm=%temp_mm:1=!%"
set "temp_mm=%temp_mm:2=@%"
set "temp_mm=%temp_mm:3=#%"
set "temp_mm=%temp_mm:4=$%"
set "temp_mm=%temp_mm:6=^%"
set "temp_mm=%temp_mm:7=&%"
set "temp_mm=%temp_mm:8=*%"
set "temp_mm=%temp_mm:9=(%"
set "temp_mm=%temp_mm:0=)%"
SETLOCAL enabledelayedexpansion
FOR %%a IN (%%) DO set "temp_mm=!temp_mm:5=%%a!"
ENDLOCAL&SET "temp_mm=%temp_mm%"
echo after:"%temp_mm%"
SET temp_
GOTO :EOF
You appear to have non-ANSI characters in your post.
Personally, I'd use sed
since actually using the variable thus-converted may be problematic.
The substitute construct targets the nominated string and replaces it with the second string. This is all well and good for most characters, but fails for some specials (like %
) because the syntax doesn't distinguish between %
being a substitute character (even when escaped by the normal %
) and being end-of-replacement-string
. The syntax of "temp_mm=%temp_mm:a=%%" and "temp_mm=%temp_mm:a=%%%" is ambiguous - is it replace with "%"
or replace with
escaped "%"
or replace with *nothing*, then add "%", "escaped-%" or "%%"
?
By using the setlocal/endlocal
bracket, you can use two-stage replacement, the first stage sets the replacement string to %
as that is the content of %%a
, but the initial parsing has then been completed, so %
is no longer a special character. The second parsing phase occurs using %
as the replacement.
Then all you need is to return the modified variable to the original context.
Upvotes: 1