批处理 - 替换变量的第N个字符

时间:2017-07-09 10:37:05

标签: batch-file variables replace substitution

我一直试图从变量中替换n个字符。这是一个例子。

String: This Will Be A 230 Bytes String

Input : 1st char, change to char 5 
       (the variable and character to change is hardcoded, so you can ignore it)

Output: 5his Will Be A 230 Bytes String

我无法弄清楚如何做到这一点。这是我尝试过的。

set remaining=237-%aircraft1Loc%
set aircraft1LocB=%aircraft1Loc%-1
call set LowTrack=%OrgLowTrack:~0,%
call set LowTrack=%%OrgLowTrack:~0,%aircraft1LocB%%%5 %%OrgLowTrack,%aircraft1Loc%,%remaining%%

这是%OrgLowTrack%

                             {0C}+{#}                                                `.:////////::--.`     ``.....``````                      ``.``  ``         ````                                             ```     ``..```             
  • LowTrack现在应该包含替换后的字符串。
  • Aircraft1Loc默认为231,每次上述脚本运行时减少1(此处未显示set /a var-=1 - )
  • 剩下的是237 - aircraft1Loc
  • aircraft1LocB是aircraft1Loc - 1

结果应该是

Original: XXXXXXXX(String shortened)
Output  : XXXXXXX5
2nd out : XXXXX5XX - This occurs when the snippet is run again

但我的片段输出:

Original: XXXXXXXX
Output  : XXXXXXXX5 OrgLowTrack,,237 -
2nd out : XXXXXXXX5 OrgLowTrack,,237 

1 个答案:

答案 0 :(得分:2)

完全重写了批次(需要strlen的子代码):

:: Q:\Test\2017\07\09\SO_44995458.cmd
@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
Set "string=This Will Be A 230 Bytes String"

Call :strLen string len

For /L %%i in (%len%,-1,0) Do (
  Echo !string:~0,%%i!_!string:~%%i!
)

Goto :Eof
:strLen string len
:: returns the length of a string
:: string [in]  - variable name containing the string being measured for length
:: len    [out] - variable to be used to return the string length
:$source http://www.dostips.com/DtTipsStringOperations.php#Function.strLen
SETLOCAL ENABLEDELAYEDEXPANSION
set "str=A!%~1!"
set "len=0"
for /L %%A in (12,-1,0) do (set /a "len|=1<<%%A"
  for %%B in (!len!) do if "!str:~%%B,1!"=="" set /a "len&=~1<<%%A"
)
ENDLOCAL & IF "%~2" NEQ "" SET /a %~2=%len%
EXIT /b