我有以下批處理腳本,它用{path}路徑替換文本檔案中的出現:
@echo off
setlocal EnableDelayedExpansion
set myPath=C:\Program Files (x86)\foo
for /F "tokens=*" %%A in (template.txt) do (
set line=%%A
set line=!line:{path}=%myPath%!
echo !line!
)
當我運行此腳本時,我收到錯誤訊息
\foo! was unexpected at this time.
如果我洗掉路徑中的括號,它會按預期作業。我怎么解決這個問題?我不能在文本檔案中的路徑周圍加上引號,因此在 set 陳述句中的路徑周圍加上引號不是一種選擇。
uj5u.com熱心網友回復:
@echo off
setlocal EnableDelayedExpansion
set "mypath=C:\Program Files (x86)\foo"
for /F "tokens=*" %%A in (q71593680.txt) do (
set "line=%%A"
CALL :changeline
echo !line!
)
FOR %%c IN ("%mypath%") DO for /F "tokens=*" %%A in (q71593680.txt) do (
set "line=%%A"
set "line=!line:{path}=%%~c!"
echo !line!
)
GOTO :EOF
:changeline
set "line=!line:{path}=%mypath%!"
GOTO :eof
問題是)替換字串中的 被視為 的右括號do。
解決方案:如圖所示制作一個內部子程式。
用于set "var1=data"設定字串值 - 這可以避免尾隨空格引起的問題。
不要path用作變數名 - 它是批處理的保留字,表示搜索目錄以查找不在當前目錄中的可執行檔案的順序。
uj5u.com熱心網友回復:
首先使用set path=%ProgramFiles(x86)%\foo(這個檔案夾可能在別處,這個變數無論如何都在這里找到它),并set用引號將替換括起來(見下文)。
修正程式:
@echo off
setlocal EnableDelayedExpansion
set pathval=%ProgramFiles(x86)%\foo
for /F "tokens=*" %%A in (template.txt) do (
set line=%%A
REM Please note the quotes around the affectation. It avoids an interpretation.
set "line=!line:{path}=%pathval%!"
echo !line!
)
旁注:即使使用setlocal,也要避免命名變數path...
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/449368.html
標籤:批处理文件
上一篇:使用批處理從請求中獲取值的問題
