Skip navigation

JSI Tip 4005. How can I copy sub-folders, based on a mask?


If you wish to copy the sub-folders, and their contents, from one folder to another, based upon the sub-folder name meeting the requirements of a mask, maskcopy.bat will do it. The syntax is:

maskcopy source mask target

where:

source   is the path to the source folder. Example "C:\Documents and Settings".

mask     is a string that specifies the matching. If the string does NOT end in a asterisk (*),
                the source sub-folder length must be equal to the mask length. Examples:
                J*      will copy all sub-folders that begin with a J or j.
                J??     will copy all sub-folders that are 3 characters in length and start with a J or j.
                ?ABC*   will copy all sub-folders that start with any character, have ABC or abc as it's
                        2nd, 3rd, and 4th characters.
                ?ABC?   will copy all sub-folders that start with any character, have ABC or abc as it's
                        2nd, 3rd, and 4th characters, and is 5 characters in length.
                ?ABC    will copy all sub-folders that start with any character, have ABC or abc as it's
                        2nd, 3rd, and 4th characters, and is 4 characters in length.

Target   is the path to the target folder. Example: D:\Users.
maskcopy.bat contains:
@echo off
setlocal
if not exist %1 goto syntax
if not exist %3 goto syntax
set source=%1
set mask=%2
set target=%3
set target=%target:"=%
set smask=%source%\%mask%
set smask="%smask:"=%*"
set source=%source:"=%
set source=%source%set work=%mask%!
set /a cnt=-1
:mcl
set /a cnt=%cnt% + 1
call :len %cnt%
if NOT "%char%" EQU "!" goto mcl
set /a cnt=%cnt% - 1
call :len %cnt%
set last=%char%
:mok
for /f "tokens=*" %%i in ('dir /s /b /ad %smask%') do call :parse "%%i"
endlocal
goto :EOF
:syntax
@echo Syntax: maskcopy Source Mask Target
endlocal
goto :EOF
:parse
set new=%1
for /f "Tokens=*" %%j in ('@echo %%new:%source%^=%%') do set sub=%%j
set sub=%sub:"=%
if "%last%" EQU "*" goto xcpy
set work=%sub%!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
call :len %cnt%
if "%char%" EQU "!" goto :EOF
if "%last%" EQU "?" goto xtst
if /i NOT "%char%" EQU "%last%" goto :EOF
:xtst
set /a cnt=%cnt% + 1
call :len %cnt%
if NOT "%char%" EQU "!" goto :EOF
:xcpy
xcopy %new% "%target%\%sub%" /s /i /y
goto :EOF
:len
for /f "Tokens=*" %%i in ('@echo %%work:~%1^,1%%') do set char=%%i


Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish