【问题标题】:Batch - Replace Nth Character of variable批处理 - 替换变量的第 N 个字符
【发布时间】:2017-07-09 10:37:05
【问题描述】:

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

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}+{#}                                                `.:////////::--.`     ``.....``````                      ``.``  ``         ````                                             ```     ``..```             
  • Lo​​wTrack 现在应该包含被替换的字符串。
  • 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

但我的 sn-p 输出:

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

【问题讨论】:

  • Set "string=This Will Be A 230 Bytes String"Set "string=5%string:~1%" 应该做你想做的事。
  • @LotPings 我明白了:5This Will Be....
  • 您是批量尝试还是从 cmd 行尝试?是否启用了扩展程序?
  • @LotPings 来自启用了扩展的批处理文件
  • 请将OrgLowTrack 发布为文本而不是图像!

标签: batch-file variables replace substitution


【解决方案1】:

完全重写批处理(需要一个子用于 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

【讨论】:

  • 所以.. 我希望输出为XXXX5,下一轮:XXX5X,所以我是否将~1 更改为~-1
  • 这将只返回字符串中的最后一个字符。使用set /?查看set的语法或访问ss64.com/nt/set.html
  • 我明白了。那我怎样才能产生我想要的结果呢?
  • 我还不清楚,你想要实现什么。添加了一行以将最后一个字符更改为批处理
  • 所以我想让脚本输出 XXXXX, XXXX5, 然后 XXX5X, XX5XX, X5XXX, 5XXXX, 然后 XXXXX
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2020-04-10
相关资源
最近更新 更多