Squashman's solution searches for a substring and replaces it with something else.
You want to replace based on position, not a substring.
You attempted to use delayed expansion (which is a good idea if you are dealing with special characters like ^ & > | < etc.) But you did not enable delayed expansion properly. Your substring syntax was also incorrect.
You can't really replace a character by position like that. Instead you have to build a new string by concatenating the beginning substring, your new text, and then the final substring.
From the command line you could do
Code: Select all
cmd /v:on
set var=asdfg
echo !var:~0,1!OK!!var:~2!
Normally you would do something like this from a batch file, in which case you can use SETLOCAL to enable delayed expansion. Also you need to escape the ! character in a batch file whenever delayed expansion is enabled so that cmd.exe does not attempt to expand it. If enclosed within quotes then you can escape it simply as "^!". But if not within quotes then you must escape it as ^^^! Finally, if you are setting a variable to the new value, then you can enclose the entire expression in quotes and use the simpler escape sequence, yet the quotes won't be included in the value.
Code: Select all
@echo off
setlocal enableDelayedExpansion
set var=asdf
echo "!var:~0,1!OK^!!var:~2!"
echo !var:~0,1!OK^^^!!var:~2!
set "var=!var:~0,1!OK^^^!!var:~2!"
set var
Since your sample string does not contain any special characters, you don't need delayed expansion. In this case you don't need to escape the ! Note that I explicitly disabled delayed expansion, though normally it is the default state.
Code: Select all
@echo off
setlocal disableDelayedExpansion
set var=asdf
echo %var:~0,1%OK!%var:~2%
set var=%var:~0,1%OK!%var:~2%
set var
Dave Benham