這是替換所有空格字符您的代碼略有修改:
@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
代碼):
>type model-tim-valid-pgm.txt
###
>xxd -g1 model-tim-valid-pgm.txt
0000000: 23 23 23 0d 0a ###..
正如你所看到的,存在model-tim-valid-pgm.txt
沒有尾隨空間。現在,腳本運行和tim-valid-pgm.mac
由:
>script.bat ABC123
>type 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 )。如果你看看你的代碼,尾部空間出現在這裏:echo !str! >> tim-valid-pgm.mac
在這個聲明:!str!
[空間] >>
。爲了避免這種情況,用更好的代碼風格:
@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
>type 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!
後。
你的意思是:使長話短說:-) – Endoro
@Endoro呵呵也許你應該已經有了解決方案,那麼說明。 – foxidrive