Search code examples
batch-filecmdcopypipefindstr

Piping string with folders in variable to findstr - copy and rename files


I'm trying to pipe a string that contains folder paths to findstr to search for a particular part in the names of the given folders - or at least, that is what I'm planning to do.

I've got a source folder with files that have to be copied into multiple subfolders and after that, one of the copied files has to be renamed corresponding to the destination folder. If there already are files with the same names, they have to be overwritten. I am trying to achieve this via .bat-file using the following commands in my code:

pushd ..\..\destination_folder\

FOR /F "delims=" %%i in ('dir /AD /S /B^| findstr /I "._Modul_X$"') do copy ..\xxx\yyy\ressources\*.* %%i
& ren %%i\xxxx_Modul_X.BAT_TEMPLATE" "%%i_Modul_X.BAT_TEMPLATE  

The copy-part seems to work, the rename-part does not and when it comes to overwriting the one file that has to be renamed after copying it (name conflict!), I'm pretty clueless how to do this (IF EXIST & DEL?).


Solution

  • If I understand the process you're attempting, then the following should do as you require, subject to my assumption that xxxx is a sequence of exactly four, digits (directory names), and characters (file names):

    @Echo Off
    SetLocal EnableExtensions
    
    PushD "..\..\destination_folder" 2>NUL || GoTo :EOF
    If Not Exist "..\xxx\yyy\resources\*.*" GoTo :EOF
    
    For /F "Delims=" %%G In (
        'Dir /B /S /A:D "????_Modul_X" 2^>NUL ^|%__AppDir__%findstr.exe^
         /I /R "\\[0123456789][0123456789][0123456789][0123456789]_Modul_X"'
    ) Do (
        For /F "Delims=" %%H In (
            '%__AppDir__%where.exe /F "%%G":"????_Modul_X.BAT_TEMPLATE" 2^>NUL'
        ) Do Del /A /F %%H
        Copy /Y "..\xxx\yyy\resources\*.*" "%%G" 1>NUL
        For /F "Delims=" %%I In (
            '%__AppDir__%where.exe /F "%%G":"????_Modul_X.BAT_TEMPLATE" 2^>NUL'
        ) Do If /I Not "%%~nxI" == "%%~nxG%%~xI" Ren %%I "%%~nxG%%~xI"
    )
    

    Please note that you will probably need to modify both instances of xxx\yyy\resources, (lines 5 and 14), as nobody really uses names like that, paying special attention to the spelling, I've used resources above, not ressources.