Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

windows - Loop through file names in a Batch Script

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

: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:UsersFamilyDesktopExampledoc 1.txt
C:UsersFamilyDesktopExampledoc 2.txt
Done

But I Get this:

running loop test
C:UsersFamilyDesktopExampleC:UsersFamilyDesktopExample
C:UsersFamilyDesktopExampledoc 1.txt
C:UsersFamilyDesktopExampledoc 2.txt
Done
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

It could be

@ECHO off
title Test
set "dir1=C:UsersFamilyDesktopExample"

: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(UsersFamilyDesktopExample)
n=filename(test1) (without extension)

f=full filename(C:UsersFamilyDesktopExampleest1.txt).

The possible modifiers are explained here FOR /?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...