循环遍历批处理脚本中的文件名

发布于 2024-10-11 09:15:57 字数 728 浏览 4 评论 0原文

我想要一个文件夹中所有文本文档的批处理脚本。 这是我到目前为止所管理的:

@ECHO off
title Test
set dir1=C:\Users\Family\Desktop\Example

:Start
cls
echo 1. test loop
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto test
if %choice%==2 exit

:test
cls
echo running loop test 
FOR %%n in (%dir1% *.txt) DO echo %dir1%\%%n
echo Done
pause

我想要输出的是:

running loop test
C:\Users\Family\Desktop\Example\doc 1.txt
C:\Users\Family\Desktop\Example\doc 2.txt
Done

但是我得到了这个:

running loop test
C:\Users\Family\Desktop\Example\C:\Users\Family\Desktop\Example
C:\Users\Family\Desktop\Example\doc 1.txt
C:\Users\Family\Desktop\Example\doc 2.txt
Done

I would like a batch script to all the text documents in a folder.
This is what I have managed so far:

@ECHO off
title Test
set dir1=C:\Users\Family\Desktop\Example

:Start
cls
echo 1. test loop
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto test
if %choice%==2 exit

:test
cls
echo running loop test 
FOR %%n in (%dir1% *.txt) DO echo %dir1%\%%n
echo Done
pause

What I would like outputted is:

running loop test
C:\Users\Family\Desktop\Example\doc 1.txt
C:\Users\Family\Desktop\Example\doc 2.txt
Done

But I Get this:

running loop test
C:\Users\Family\Desktop\Example\C:\Users\Family\Desktop\Example
C:\Users\Family\Desktop\Example\doc 1.txt
C:\Users\Family\Desktop\Example\doc 2.txt
Done

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最舍不得你 2024-10-18 09:15:57

主要问题似乎是 (%dir1% *.txt) 之间的空格,

引号可能是

@ECHO off
title Test
set "dir1=C:\Users\Family\Desktop\Example"

:Start
cls
echo 1. test loop
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto test
if %choice%==2 exit

:test
cls
echo running loop test 
FOR %%X in ("%dir1%\*.txt") DO echo %%~dpnX
echo Done
pause

为了避免路径中空格或其他特殊字符的问题。

编辑:
%%~dpnX 用于将%%X 的文件名扩展为
d=驱动器(C:)
p=路径(\Users\Family\Desktop\Example)
n=文件名(test1)(不带扩展名)

f=完整文件名(C:\Users\Family\Desktop\Example\test1.txt)。

此处解释了可能的修饰符FOR /?

The main problem seems to be the space between (%dir1% *.txt)

It could be

@ECHO off
title Test
set "dir1=C:\Users\Family\Desktop\Example"

:Start
cls
echo 1. test loop
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto test
if %choice%==2 exit

:test
cls
echo running loop test 
FOR %%X in ("%dir1%\*.txt") DO echo %%~dpnX
echo Done
pause

The quotes are for avoiding problems with spaces or other special characters in the path.

EDIT:
The %%~dpnX is for expanding the filename of %%X to
d=drive(C:)
p=path(\Users\Family\Desktop\Example)
n=filename(test1) (without extension)

f=full filename(C:\Users\Family\Desktop\Example\test1.txt).

The possible modifiers are explained here FOR /?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文