在批处理文件中执行子字符串的最佳方法是什么?

时间:2009-03-11 21:08:16

标签: batch-file substring

我想获取当前正在运行的批处理文件的名称没有文件扩展名。

感谢this link,我的文件名为为扩展程序...但是在批处理文件中执行子字符串的最佳方法是什么?

或者是否有另一种方法来获取没有扩展名的文件名?

在这种情况下,可以安全地假设3个字母的扩展名。

3 个答案:

答案 0 :(得分:376)

好吧,只需使用%~n0获取批处理的文件名即可。

@echo %~n0

将输出当前运行的批处理文件的名称(不带扩展名)(除非在call调用的子例程中执行)。在帮助的最后,可以使用help for找到路径名称的此类“特殊”替换的完整列表:

  

另外,替换FOR   变量引用已得到增强。   您现在可以使用以下可选项   语法:

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

要准确回答您的问题,请使用:~start,length表示法完成子字符串:

%var:~10,5%

将从环境变量%var%中的位置10提取5个字符。

注意:字符串的索引基于零,因此第一个字符位于第0位,第二个字符位于1,等等。

要获取参数变量的子字符串,例如%0%1等,您必须首先使用set将它们分配给普通环境变量:

:: 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

答案 1 :(得分:35)

上面很好地解释了!

对于那些可能像我这样受苦的人来说,在本地化的Windows(我的是斯洛伐克的XP)中工作,你可以尝试用%替换!

所以:

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

答案 2 :(得分:13)

作为Joey答案的补充信息,set /?for /?的帮助中没有说明。

%~0扩展为自己批次的名称,与输入的名称完全相同 因此,如果您启动批处理,它将被扩展为

%~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中,总是扩展为函数的名称,而不是批处理文件的名称。
但是如果你使用至少一个修饰符,它将再次显示文件名!

相关问题