In a specified folder, how can I recursively delete everything except “.mkv” and “.nfo” files?

Posted on

QUESTION :

I’m trying to figure out the code for a batch-file (Windows) that In a specified folder recursively deletes everything except files with a certain extension (i.e. .mkv and .nfo)?

Something like this, but for the above.

def deleteRootFolder = tryQuietly{ root.toBoolean() }

/*
 * Delete orphaned "clutter" files like nfo, jpg, etc and sample files
 */
def isClutter(f) {
    def exts    = tryQuietly{ exts }            ?: /jpg|jpeg|png|gif|nfo|xml|htm|html|log|srt|sub|idx|md5|sfv|txt|rtf|url|db|dna|log/
    def terms   = tryQuietly{ terms }           ?: /sample|trailer|extras|deleted.scenes|music.video|scrapbook/
    def maxsize = tryQuietly{ maxsize as Long } ?: 100 * 1024 * 1024

    // path contains blacklisted terms or extension is blacklisted
    return (f.extension ==~ "(?i)($exts)" || f.path =~ "(?i)\b($terms)\b") && f.length() < maxsize
}


def clean(f) {
    println "Delete $f"

    // do a dry run via --action test
    if (_args.action == 'test') {
        return false
    }

    return f.isDirectory() ? f.deleteDir() : f.delete()
}


// delete clutter files in orphaned media folders
args.getFiles{ isClutter(it) && !it.dir.hasFile{ (it.isVideo() || it.isAudio()) && !isClutter(it) }}.each { clean(it) }

// delete empty folders but exclude given args
args.getFolders().sort().reverse().each { if (it.listFiles().length == 0) { if (deleteRootFolder || !args.contains(it)) clean(it) } }

ANSWER :

Here’s one quick way of doing this among many:

@echo off
set extlist=mkv nfo
set rootfolder="C:Video Folder"
pushd %rootfolder%
if not ["%cd%"]==[%rootfolder%] echo Aborting as unable to change to %rootfolder% && goto End
attrib /s /d -r
for %%a in (%extlist%) do attrib /s *.%%a +r
del. /s /q
:End
popd

Run on a test dir first with a few files that you want to retain and others you want to delete, before unleashing on your main dir. If you want the batch file to request delete confirmation for every file, change del. /s /q to del. /s /p.

this is an other way without the need to change attributes, look at the output & remove echo, if OK:

@echo off &setlocal
set "extlist=.mkv|.nfo|"
for /r "c:video" %%i in (*) do (
    set "fname=%%~i"
    setlocal enabledelayedexpansion
    if "!extlist:%%~xi|=!"=="%extlist%" echo del "!fname!"
    endlocal
)

Leave a Reply

Your email address will not be published.