开发者

Loop through file names in a Batch Script

开发者 https://www.devze.com 2023-02-03 22:46 出处:网络
I would like a batch script to all开发者_开发百科 the text documents in a folder. This is what I have managed so far:

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


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 /?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号