Penny
Penny

Reputation: 816

Delete all files except filenames with specific string

I have 1000's of files like TOP_QUERIES-abc.com.au.csv,TOP_QUERIES-www.abc.com.au.csv, TOP_QUERIES-m.lmn.com.au.csv, TOP_QUERIES-blog.com.au.csvand get-files.php

Is it possible to delete all the .csv files from a folder except for files starting with blog. ,m. , www, and .php from the folder?

I know its possible in php but how can I achieve in batch file?

Upvotes: 2

Views: 1276

Answers (1)

Magoo
Magoo

Reputation: 80213

@ECHO OFF
SETLOCAL
SET "targetdir=U:\destdir"
SET "exclude=blog. m. www."
FOR /f "delims=" %%a IN (
 'dir /b /a-d "%targetdir%\*.csv" '
 ) DO (
 ECHO %%a | findstr /B /L "%exclude%" >NUL
 IF ERRORLEVEL 1 ECHO(DEL "%targetdir%\%%a"
)

GOTO :EOF

This should get the task done for you. You would need to change the setting of targetdir to suit your circumstances.

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.

The .php files are excluded because they don't match the *.csv filename - or did you want to not-delete files starting .php? If so, simply add .php into the exclude variable...


Revision for efficiency:

@ECHO OFF
SETLOCAL
SET "targetdir=U:\destdir"
SET "exclude=blog. m. www."
FOR /f "delims=" %%a IN (
 'dir /b /a-d "%targetdir%\*.csv" ^| findstr /B /L "%exclude%"'
 ) DO (ECHO(DEL "%targetdir%\%%a"
)

GOTO :EOF

Upvotes: 3

Related Questions