0

I've been working on this batch script with which i want to copy random files from one folder to another and every thing is fine but i can't copy a file if there is space in it's name and i can't put a variable after delims what should i do help

this is my code

@echo off
:1
set num=0
cls
set /p input=enter the number of total files: 
set /p input1= enter the number of files you want: 
set /p address= enter the address of your files:

FOR /f "tokens=1*delims=:" %%b IN ('dir /b /a-d "%address%\*" ^|findstr /n /V ":"') DO ECHO.%%b: %%c>> filename.txt
md SelectedFiles
:2

set /a l= 1+1
set /a num=%num%+1
set /a n=%random% %% %input% +1

for /f "tokens=1* delims='%n%:'" %%a in (filename.txt) do if 2==%l% set file=%%b

timeout 1

echo %n% %file%
copy %file% SelectedFiles

if %num% lss %input1% goto 2

echo your files have been copied

pause
goto 1
Curious
  • 43
  • 6
  • @Stephan I have add the change you told me to do but it says **The system cannot find the file specified.** – Curious Nov 19 '22 at 14:37
  • @Stephan, you can use variables within `for /F` options as long as they are `%`-expanded; delayed expanded ones cannot be used, neither can be used loop-variables… – aschipfl Nov 19 '22 at 15:49
  • Try `(ECHO/%%b:%%~fc)>"filename.txt"`. `%%~fc` returns the full `D:\rive\folder\filename.ext`, the parentheses are a safeguard against (rare) quirky filenames (better safe than sorry). Most important: remove the space after the colon (it gets part of `%%c`) – Stephan Nov 19 '22 at 16:04
  • @Stephan, everything is working fine but I can't copy file to selectedFiles I echoed file and n, n is random but I can't get file name of any other file than the last file, and sorry for too many replies thanks – Curious Nov 19 '22 at 18:20
  • @Stephan, I tried putting the output of the for loop in the 2 section into a txt file and it seems like it copies a lot of random file names and in the end there is the name of the last file please can you come up with a new for loop – Curious Nov 19 '22 at 19:02
  • There is a way to shorten the code a bit; You can get the number of files **with the extension** in the selected path, by the following code: `for /f %%n in ('dir /b "%address%" ^| find /c "."') do if not "%%n" == "" set "FilesCount=%%n"` – yonni Nov 20 '22 at 09:21
  • Or if you want the number of folders as well, do it like this: `for /f %%n in ('dir /b "%address%" ^| find /v /c ":"') do if not "%%n" == "" set "Count=%%n"` – yonni Nov 20 '22 at 09:27
  • 1. Remove the `'` from `delims=` as you do not want them to be delimiters too. 2. What is the always true condition `if 2==%l%` for? 3. To leave a `for` loop after the first iteration, put `goto :NEXT` into its body as the last command, and put label `:NEXT` immediately after the loop… – aschipfl Nov 20 '22 at 12:05
  • `if 2==%l%` should probably be `if "%%a" == "%n%` to select the `n`th file. – Stephan Nov 20 '22 at 15:29

0 Answers0