0

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)

wb6vpm
  • 23
  • 5
  • Does it have to be `cmd` ? You will have to do loops and recursive calls, but internal `for` should be able to do this. – NiKiZe Aug 31 '21 at 19:20
  • I was wrong on the recursive calls things, at least from what I understand from the question, but might be wrong? Maybe it should only check for "example.txt"? – NiKiZe Aug 31 '21 at 19:45
  • Unfortunately, yes, I'm looking to add this to an existing batch file, where I need to replace existing files that have been updated (non-zero size) with the original 0 byte size file, and the file exists in multiple subfolders that can change, so I can't just hardcode every possible (sub)folder to just wipe and restore. – wb6vpm Sep 10 '21 at 21:43

1 Answers1

1

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

NiKiZe
  • 1,246
  • 8
  • 20
  • Thank you very much! I had to make a few tweaks to get it to cooperate, but this gave me a very good starting point! – wb6vpm Sep 14 '21 at 01:57