Looking for a way to replace every instance of a non-zero sized file in a directory tree using a batch file

I am trying to figure out a way to have a batch script overwrite every instance of a non-zero byte file inside of a specific directory and its sub-folders. I'm guessing since I'm looking for a non-zero file I could probably loop it with a escape if it doesn't find any non-zero sized file?

Example, overwrite every instance of example.txt where it is a non-zero filesize:

D:\
\---SubFolder1
    |   example.txt <10 bytes>
    |
    \---Subfolder2
        |   example.txt <0 bytes>
        |
        \---Subsubfolder1
                example.txt <20 bytes>

In the example, D:\Subfolder1\example.txt, and D:\Subfolder2\Subsubfolder1\example.txt would be overwritten, but D:\Subfolder2\example.txt wouldn't be changed.

Thank you to @NiKiZe for all your help!

Working Code:

@ECHO OFF

SET DPATH=%~dp0

FOR /R "%DPATH%" %%F IN (*** SEE BELOW) DO IF %%~zF GTR NEQ 0 CALL :NonEmptyFile "%%~F"
GOTO :EOF

:NonEmptyFile
ECHO Got non empty file: %1
CALL :EOF

*** Replace with filename that you are wanting to replace, be sure to use a single character wildcard somewhere (I used it in the extension - for example, if I am searching for example.txt, I replaced the * with example.t?t)


Minimal batch that walks a given path and all subfiles and subpaths, calling the NonEmptyFile label for every non empty file.

@ECHO OFF

SET DPATH=%~dp0

FOR /R "%DPATH%" %%F IN (*) DO IF %%~zF GTR 0 CALL :NonEmptyFile "%%~F"
GOTO :EOF

:NonEmptyFile
  ECHO Got non empty file: %1
CALL :EOF

By using %~1 in the function it will be expanded and you can use something like COPY /Y "somefile.txt" "%~1" How you want to overwrite the files was not specified.

Another option to create "empty files" is ECHO. > "%~1"

Explanation:

  • FOR /R "%DPATH%" %%F IN (*) DO walks every file
  • IF %%~zF GTR 0 if file size is greater than ...
  • CALL :NonEmptyFile "%%~F" Call the :NonEmptyFile label with the filename escaped

To test this at prompt, use FOR /R "D:\SubFolder1\" %F IN (*) DO IF %~zF GTR 0 ECHO NonEmptyFile "%~F"

More info on how for works is given by running for /? in cmd