3 回答

TA貢獻1796條經(jīng)驗 獲得超4個贊
好吧,只是獲取批處理的文件名最簡單的方法就是使用%~n0。
@echo %~n0
將輸出當前運行的批處理文件的名稱(不帶擴展名)(除非在調(diào)用的子程序中執(zhí)行call)。help for在幫助的最后可以找到路徑名稱的這種“特殊”替換的完整列表:
此外,F(xiàn)OR變量引用的替換已得到增強。您現(xiàn)在可以使用以下可選語法:
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
可以組合修飾符以獲得復合結(jié)果:
%~dpI - expands %I to a drive letter and path only
%~nxI - expands %I to a file name and extension only
%~fsI - expands %I to a full path name with short names only
但是,要準確回答您的問題:使用:~start,length符號來完成子字符串:
%var:~10,5%
將從環(huán)境變量中的位置10提取5個字符%var%。
注意:字符串的索引是零,所以第一個字符位于0,第二個字符位于1,等等。
為了得到參數(shù)變量如子%0,%1等你給他們分配使用正常的環(huán)境變量set第一:
:: Does not work:
@echo %1:~10,5
:: Assign argument to local variable first:
set var=%1
@echo %var:~10,5%
語法更強大:
%var:~-7% 從中提取最后7個字符 %var%
%var:~0,-4%將提取除最后四個之外的所有字符,這些字符也可以消除文件擴展名(假設(shè)在句點[ .] 之后有三個字符)。
有關(guān)help set該語法的詳細信息,請參閱

TA貢獻1776條經(jīng)驗 獲得超12個贊
很好地解釋了上面!
對于那些可能像我一樣受苦的人來說,在本地化的Windows(我的是斯洛伐克的XP)中工作,你可以嘗試%
用一個替換!
所以:
SET TEXT=Hello WorldSET SUBSTRING=!TEXT:~3,5!ECHO !SUBSTRING!

TA貢獻1898條經(jīng)驗 獲得超8個贊
作為一個額外的信息,以Joey的答案,這是不是在幫助說明set /?
,也沒有for /?
。
%~0
擴展為自己批處理的名稱,與輸入的名稱完全相同。
因此,如果您啟動批處理,它將被擴展為
%~0 - mYbAtCh%~n0 - mybatch%~nx0 - mybatch.bat
但是有一個例外,在子程序中擴展可能會失敗
echo main- %~0call :myFunctionexit /b:myFunctionecho func - %~0echo func - %~n0exit /b
結(jié)果是
main - myBatchFunc - :myFunctionfunc - mybatch
在函數(shù)中,%~0
總是擴展為函數(shù)的名稱,而不是批處理文件的名稱。
但是如果你使用至少一個修飾符,它將再次顯示文件名!
添加回答
舉報