首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用批处理文件获取文件名的步骤

使用批处理文件获取文件名的步骤
EN

Stack Overflow用户
提问于 2018-02-01 20:48:41
回答 2查看 145关注 0票数 0

我已经写了批处理文件来提取文件夹中多个文件的最后8个字符。但是批处理文件没有给出期望的结果。我的文件夹由下面提到的文件名sub_rachit_01.pdf和sub_kapoor_02.pdf组成。我想从文件夹中提取rachit_01和kapoor_02作为变量。批处理文件切碎如下:

代码语言:javascript
复制
@echo off

set /p location=Please enter location of .pdf files:

SETLOCAL ENABLEDELAYEDEXPANSION 
for /f "tokens=*" %%a in ('dir /b %location%\*.pdf') do (
set filename=%%~na

set file=%filename:~-8%
echo %file%
)

pause
EN

回答 2

Stack Overflow用户

发布于 2018-02-01 22:11:32

根据我的评论:

代码语言:javascript
复制
@Echo Off
:AskInput
ClS
Set "location="
Set /P "location=Please enter location of .pdf files: "
If Not Exist "%location%\*.pdf" GoTo AskInput

SetLocal EnableDelayedExpansion
For %%A In ("%location%\*.pdf") Do (Set "filename=%%~nA"
    Set "filename=!filename:~-8!"
    Echo !filename!)

Pause

我已经用一个普通的For循环替换了您的For /F循环,为用户输入设置了一些保护措施,并删除了一个额外的变量,即动态改变filename

票数 1
EN

Stack Overflow用户

发布于 2018-02-01 20:54:22

首先,你enabledelayedexpansion但从不使用它。此外,%%~na将显示不包括分机的名称。如果所有文件实际上都包含sub_,则可以进行搜索和替换。

代码语言:javascript
复制
@echo off

set /p location=Please enter location of .pdf files:

SETLOCAL ENABLEDELAYEDEXPANSION 
for /f "tokens=*" %%a in ('dir /b %location%\*.pdf') do (
set "filename=%%~na"
set "filename=!filename:sub_=!"
echo !filename!
)
endlocal
pause

通过执行for /?

代码语言:javascript
复制
%~I                     Expands %I which removes any surrounding 
                    quotation marks ("").
%~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                    Expands path to contain short names only.
%~aI                    Expands %I to the file attributes of file.
%~tI                    Expands %I to the date and time of file.
%~zI                    Expands %I to the 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 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48563161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档