I'd like to delete a bunch of files in a folder that have a specific extension and do not match a specified string

StackOverflow https://stackoverflow.com/questions/22599179

  •  19-06-2023
  •  | 
  •  

Question

I am new to command prompt scripting and batch files. I have a folder with the following:

  • file1.pdf
  • file1.tif
  • file1_cropped.tif
  • file1.txt
  • file2.pdf
  • file2.tif
  • file2_cropped.tif
  • file2.txt...
  • filen.pdf
  • filen.tif
  • filen_cropped.tif
  • filen.txt

I would like to delete all the tif files that do not have "_cropped" in the filename. I have seen a few solutions for deleting files that have a specified extension, or that match a specific string, but I am trying to combine the two.

Much thanks,

Marc.

Was it helpful?

Solution 2

From command line, being in target directory:

for /F "eol=: delims=" %a in ('dir /b *.tif ^| find /V "_cropped"') do @del "%a"

Where we have:

FOR /F ["options"] %variable IN ('command') DO command [command-parameters]

In batch file:

for /F "eol=: delims=" %%a in ('dir /b *.tif ^| find /V "_cropped"') do @del "%%a"

A sample where we use a more interactive approach with confirmation:

Use typically as:

the_bat_file.bat exclude_these tif

Where option one is string in file names to exclude and two is file extension.

@echo off

set pat=_cropped
set ext=tif

IF "%1"=="--help"  (
    echo Usage %0 [exclude] [extension]
    echo   Default exclude  : %pat%
    echo   Default extension: %ext%
    goto end
)

GOTO part1

:confirm
SET /P CONF=Continue y/N?
IF /I "%CONF%" NEQ "Y" GOTO end
goto %con%

:part1
setlocal

IF NOT "%1"=="" set pat=%1
IF NOT "%2"=="" set ext=%2

echo Pattern  : %pat% 
echo Extension: %ext%
echo.

set con=part2
goto confirm

:part2
echo.
echo Files to delete:
echo.
for /F "eol=: delims=" %%a in ('dir /b "*.%ext%" ^| find /V "%pat%"') do echo "%%a"
echo.
set con=part3
goto confirm

:part3
for /F "eol=: delims=" %%a in ('dir /b "*.%ext%" ^| find /V "%pat%"') do DEL "%%a"

:end
endlocal

OTHER TIPS

for /f "delims=" %%a in ('dir /b /a-d *.tif^|find /v /i "_cropped"') do echo del "%%a"

should suit.

perhaps you'd want

pushd "target directoryname"
for /f "delim...
popd

to specify a directory other than your current to be processed.

The required DEL commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO DEL to DEL to actually delete the files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top