在batch file中执行子string的最佳方法是什么?

我想获得当前正在运行的batch file的名称, 而没有文件扩展名。

由于这个链接 ,我有扩展名的文件名…但在batch file中做一个子string的最佳方法是什么?

还是有另一种方式来获得文件名W / O扩展名?

在这种情况下假设3个字母的扩展是安全的。

那么,为了得到你的batch file,最简单的方法就是使用%~n0

 @echo %~n0 

将输出当前正在运行的batch file的名称(不带扩展名)(除非在调用的子程序中执行)。 path名称的这些“特殊”replace的完整列表可以在help for的最后find帮助:

另外,FORvariables引用的replace已被增强。 您现在可以使用以下可选语法:

 %~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 

修饰符可以组合得到复合结果:

 %~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 

但是,要精确地回答你的问题:子string使用:~start,length符号来完成:

 %var:~10,5% 

将从环境variables%var%位置10提取5个字符。

注:string的索引是基于零的,所以第一个字符位于0,第二个位于1等。

为了获得参数variables(如%0%1等)的子string,您必须先使用set将它们分配给一个正常的环境variables:

 :: Does not work: @echo %1:~10,5 :: Assign argument to local variable first: set var=%1 @echo %var:~10,5% 

语法更强大:

  • %var:~-7%%var%提取最后7个字符
  • %var:~0,-4%会提取除最后四个字符之外的所有字符,这也会使您不知道文件扩展名(假设在[ . ]后的三个字符)。

有关该语法的详细信息,请参阅help set

上面很好地解释了!

对于所有那些可能像我一样在本地化Windows(我的是斯洛伐克语XP)中工作的人,您可以尝试用!

所以:

 SET TEXT=Hello World SET SUBSTRING=!TEXT:~3,5! ECHO !SUBSTRING! 

作为一个额外的信息,乔伊的答案,这是没有描述的set /? 也不for /?

%~0扩展到自己批处理的名称,就像input一样。
所以,如果你开始你的批处理,它将被扩展为

 %~0 - mYbAtCh %~n0 - mybatch %~nx0 - mybatch.bat 

但是有一个例外,在子程序中扩展可能会失败

 echo main- %~0 call :myFunction exit /b :myFunction echo func - %~0 echo func - %~n0 exit /b 

这导致

 main - myBatch Func - :myFunction func - mybatch 

在函数中, %~0 〜0总是扩展到函数的名字,而不是batch file。
但是如果你至less使用了一个修饰符,它会再次显示文件名!