Home > Mobile >  Replace all files in a folder with empty text file named with the replaced files
Replace all files in a folder with empty text file named with the replaced files

Time:06-27

I have a bunch of folders and inside each of those folders are multiple files (all mkv files if that matters)

What I would like to do is run through each of the folders and replace every mkv file within the folder with an empty text file named after the deleted mkv file.

The mkv files all have different names. Can this be done with a batch file and copy /b NUL EmptyFile.txt somehow?

CodePudding user response:

You can simply loop through the directories and use the variable expansion to get the name, create the text file and then delete the .mkv file:

@echo off
for /F "delims=" %%i in ('dir /b /s *.mkv') do break>"%%~dpni.txt" && del /Q /S "%%~i"

This will simply assign each file name to the metavariable %%i then expand to the drive, path and name %%~dpni and add an extension, in your case you wanted .txt using break to create an empty file.

Please first test this in a test folder before you run it on your actual files.

CodePudding user response:

FOR /F "usebackq delims=" %%A IN (`DIR /A:d /B "C:\ParentFolder"`) DO (
    FOR /F "usebackq delims=" %%B IN (`DIR /B "C:\ParentFolder\%%A"`) DO (
        DEL /Q /F "C:\ParentFolder\%%A\%%B" > NUL 2>&1
        ECHO. > "C:\ParentFolder\%%A\%%~nB.txt"
    )
)

This will search for all the folders within C:\ParentFolder, and then fetch all files within the subfolders, and then delete any found files and echo (print) a blank line to a txt file with the same name as the original file.

DIR lists all files within a given folder, /B specifies that only bare file names and extensions are to be output. /A:d specifies to list directories (folders) only.

DEL deletes files, /Q specifies quietly with no confirmation, /F forces deletion of read only files (Not really necessary in this case but whatever)

ECHO. echoes (prints) a blank line, > outputs it to the provided file (It will create the file if it doesn't exist). %%~nB specifies only the name of the file, excluding the extension.

If you are not using this in a script, the following code works as a one-liner: FOR /F "usebackq delims=" %A IN (`DIR /A:d /B "C:\ParentFolder"`) DO ( FOR /F "usebackq delims=" %B IN (`DIR /B "C:\ParentFolder\%A"`) DO DEL /Q /F "C:\ParentFolder\%A\%B">NUL 2>&1 & ECHO. > "C:\ParentFolder\%A\%~nB.txt" )

  • Related