windows 批量获取文件名 for 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1100452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:33:56  来源:igfitidea点击:

Get filename in batch for loop

windowsbatch-filecmd

提问by Murtaza Mandvi

I have the following For loop in a batch file:

我在批处理文件中有以下 For 循环:

for /R c:\test\src %%i IN (*.*) DO (
MOVE %%i C:\test\destination
ECHO %%i
exit
)

The result of the ECHO outputs the entire file path Ex: C:\Foldername\FilenameI need to ECHO out only the Filename.Is there a specific command which would give me the filename ? Thanks !

ECHO 的结果输出整个文件路径 例如:C:\Foldername\Filename我只需要 ECHO 出Filename。是否有特定的命令可以给我文件名?谢谢 !

回答by AKX

When Command Extensions are enabled (Windows XP and newer, roughly), you can use the syntax %~nF (where F is the variable and ~n is the request for its name) to only get the filename.

当启用命令扩展(Windows XP 和更新版本,大致)时,您可以使用语法 %~nF(其中 F 是变量,~n 是对其名称的请求)来仅获取文件名。

FOR /R C:\Directory %F in (*.*) do echo %~nF

should echo only the filenames.

应该只回显文件名。

回答by Chris

or Just %~F will give you the full path and full file name.

或者 Just %~F 会给你完整的路径和完整的文件名。

For example, if you want to register all *.ax files in the current directory....

例如,如果要注册当前目录中的所有 *.ax 文件....

FOR /R C:. %F in (*.ax) do regsvr32 "%~F"

This works quite nicely in Win7 (64bit) :-)

这在 Win7(64 位)中非常有效:-)

回答by Guy Soffer

I am a little late but I used this:

我有点晚了,但我使用了这个:

dir /B *.* > dir_file.txt

then you can make a simple FOR loop to extract the file name and use them. e.g:

然后你可以做一个简单的 FOR 循环来提取文件名并使用它们。例如:

for /f "tokens=* delims= " %%a in (dir_file.txt) do (
gawk -f awk_script_file.awk %%a
)

or store them into Vars (!N1!, !N2!..!Nn!) for later use. e.g:

或将它们存储到 Vars (!N1!, !N2!..!Nn!) 以备后用。例如:

set /a N=0
for /f "tokens=* delims= " %%a in (dir_file.txt) do (
set /a N+=1
set v[!N!]=%%a
)

回答by Gophern Kwok

If you want to remain both filename (only) and extension, you may use %~nxF:

如果您想同时保留文件名(仅)和扩展名,您可以使用%~nxF

FOR /R C:\Directory %F in (*.*) do echo %~nxF

回答by Martijn Dirkse

The answer by @AKX works on the command line, but not within a batch file. Within a batch file, you need an extra %, like this:

@AKX 的答案适用于命令行,但不适用于批处理文件。在批处理文件中,您需要一个额外的%,如下所示:

@echo off
for /R TutorialSteps %%F in (*.py) do echo %%~nF