这是您的代码,稍作修改:
@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
set "name=%~1"
for /f "delims=" %%a in (model-tim-valid-pgm.txt) do (
set "str=%%a"
set "str=!str:###=%name%!"
echo !str! >> tim-valid-pgm.mac
)
让我们看看会发生什么(xxd
在hex
代码中可视化文件):
>类型模型-tim-valid-pgm.txt
###
>xxd -g1 模型-tim-valid-pgm.txt
0000000: 23 23 23 0d 0a ###..
如您所见, 中没有尾随空格model-tim-valid-pgm.txt
。现在脚本正在运行并tim-valid-pgm.mac
制作:
>script.bat ABC123
>类型 tim-valid-pgm.mac
ABC123
>xxd -g1 tim-valid-pgm.mac
0000000: 41 42 43 31 32 33 20 0d 0a ABC123 ..
>for /f "delims=" %a in (tim-valid-pgm.mac) do @echo "%a"
“ABC123”
现在您可以清楚地看到尾随空格(HEX 20)。如果您查看您的代码,尾随空格出现在此处:echo !str! >> tim-valid-pgm.mac
在此语句中:!str!
[SPACE] >>
。为避免这种情况,请更好地使用以下代码样式:
@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
set "name=%~1"
for /f "delims=" %%a in (model-tim-valid-pgm.txt) do (
set "str=%%a"
set "str=!str:###=%name%!"
>> tim-valid-pgm.mac echo !str!
)
..在这里输出:
>script.bat ABC123
>类型 tim-valid-pgm.mac
ABC123
>xxd -g1 tim-valid-pgm.mac
0000000: 41 42 43 31 32 33 0d 0a ABC123..
>for /f "delims=" %a in (tim-valid-pgm.mac) do @echo "%a"
“ABC123”
现在不能有尾随空格,即使!str!
.