4

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
Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
Krayons
  • 240
  • 2
  • 5
  • 14

1 Answers1

12

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

Be Kind To New Users
  • 9,672
  • 13
  • 78
  • 125
jeb
  • 78,592
  • 17
  • 171
  • 225
  • Thank You that worked perfectly. Could you explain %%~dpfX to me? – Krayons Jan 11 '11 at 23:56
  • 3
    `%%~nX` just filename (test1), filename with extension - `%%~nxX` (test1.txt). – Artem P Jun 11 '14 at 21:03
  • 1
    To clarify: note that in his code `%%X` is the whole filename that was found. The other pieces `~dpn` are modifiers to the `%%X`. So as user 2nd said, use the `~n` modifier on the variable to output just the file by calling `echo %%~nX` – Richard Le Mesurier May 10 '15 at 12:48