Click here to Skip to main content
15,884,875 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello all,

I need to do something like this in several directories:

copy DIR_A\SUBDIR_B\SUBDIR_C\*.xyz ..\


There are a lot of SUBDIR_B that do NOT contain SUBDIR_C - I do not want to do anything in there, only in SUBDIR_B that contain SUBDIR_C.

Instead of manually looking into DIR_A\SUBDIR_*, I want to automate that.

My preferred way would be a simple .bat file. Does anybody can give me a hibt how to accomplish this?

Best Regards
Dennis
Posted

1 solution

I'm not sure about simple but here is something that appears to work. It has nested directory iterators to locate subdirectories two levels down from the start point.

Top tip: It's always a good idea to prefix any potentially harmful commands with ECHO during testing.

e.g Use ECHO COPY src dest to see what would be copied without actually doing it.

@ECHO OFF
ECHO Process files two directory levels down from the start point
REM LEVEL_1\LEVEL_2\LEVEL_3\*.*

SET LEVEL_1=c:\dir1\dir2
SET FILESPEC=*.txt

PUSHD %LEVEL_1%
ECHO.
ECHO Start point is %CD%
ECHO   Searching for files matching %FILESPEC%
ECHO.

REM enumerate LEVEL_2 directories
FOR /D %%A IN (%LEVEL_1%\*) DO (
  REM enumerate LEVEL_3 directories
  FOR /D  %%B IN (%%A\*) DO (
      PUSHD %%B
      
      REM Show directory if it contains matching files
      IF EXIST %FILESPEC% (
        ECHO.
        ECHO LEVEL_3 %%B

        REM enumerate matching files in the LEVEL_3 subdirectory
        FOR %%F IN (%FILESPEC%) DO (
          REM ~nx modifier to get name and extension only
          REM ~dp modifier to get drive and path only
          ECHO   COPY "%%~nxF" "%%~dpF.."
        )
      )
      POPD
  )
)
POPD
PAUSE


Alan.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900