6

I'm trying to get the first (any) 10 files from a deeply nested filestructure. I can use XCOPY source dest /T /E to build the folder structure, but what I'd like to do is get 10 files from each folder and sub folder and copy those as well.

Is there a tool that will do this for me?

2
  • 1
    To confirm, you want to get the first 10 files only, from a folder structure containing any number of files?
    – Cocowalla
    Commented Feb 18, 2011 at 12:44
  • Yes that's right.
    – Rob White
    Commented Feb 18, 2011 at 15:11

3 Answers 3

12

Your question sounds like you want the first 10 files from every subfolder? This ought to do it (not exhaustively tested!):

echo off
xcopy /Y %1 %2 /T /E

dir %1 /b /s /A:D >tempfolderlist.txt

for /f "tokens=1 delims=¬" %%a in (./tempfolderlist.txt) do (

    dir "%%a" /b /A:-D >tempfilelist.txt

    setlocal enabledelayedexpansion

    set counter=0

    for /f "tokens=1 delims=¬" %%b in (./tempfilelist.txt) do (

        IF !counter! LSS 10 call :docopy %1 "%%a\%%b" %2
        set /a counter+=1

    )

    endlocal
)

del /q tempfolderlist.txt
del /q tempfilelist.txt
GOTO:EOF

:docopy
set sourcePath=%~1
set sourceFile=%~2
set targetPath=%~3
set sourceNoDrive=%sourceFile:~3,5000%
set sourcePathNoDrive=%sourcePath:~3,5000%
set sourceNoDrive=!sourceNoDrive:%sourcePathNoDrive%\=!

copy "%sourceFile%" "%targetPath%\%sourceNoDrive%" >> out.txt

GOTO:EOF

If it's saved to a batch file named 'first10.cmd', you can use it like this:

first10.cmd "C:\Temp\SourcePath" "C:\Temp\DestPath"

First it prepares the destintation folder structure using xcopy, just as in your question. Then we save a list of all folders to a file, and loop over each one. For each folder, we save a list of all files in that folder, and loop over each file. For each file, :docopy builds the copy command and executes it.

1
  • 1
    seriously great answer!
    – Chopper3
    Commented Feb 18, 2011 at 15:46
2

If you only want the first 10 files out of the whole structure, you could use this (heavily borrowed from Owen's answer!)

@echo off

mkdir %2

dir %1 /b /s /A:-D >tempfilelist.txt

setlocal enabledelayedexpansion

set counter=0

for /f "tokens=1 delims=¬" %%b in (./tempfilelist.txt) do (

    IF !counter! LSS 10 call :docopy "%%b" %2
    set /a counter+=1
)

endlocal
)

del /q tempfilelist.txt
GOTO:EOF

:docopy
copy %1 %2

GOTO:EOF

Use it like:

mybatchfilename.bat "C:\Source" "C:\Target"
0

I'm almost certain you can't do this using a regular xcopy command, you're going to have to use some form of script to find the files you actually want then just pass them to xcopy one by one - that or build one hell of an 'exclude' string :)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .