在批处理文件中从路径提取文件名

人工智能 2026-07-09

我正在尝试编写一个批处理程序,用于遍历目录中的文件。我的代码像下面这样嵌套在一个循环里:

for /r "path/to/dir" %%f in (*.json) do (...)

%%f是一个完整路径,但我只想要不带目录和扩展名的文件名,所以我尝试了下面这两行来去掉它们(目录在文件名之前,总共有68个字符;扩展名在后面,总共有5个字符):

set nf=%%f:~0,68%%
set nf=%%nf:~0,-5%%

然而,echo只返回字符串 "%nf%",变量本身包含字符串 "%nf:~0,-5%"。我尝试开启延迟扩展并改用 '!',但结果只是让 !nf存储为空字符串。

有没有办法解决这个并把 "directory\filename.ext" 变成 "filename"?

解决方案

你可以使用 %%~nf 来获得文件名的基本名(不包含扩展名)。

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
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章