Joe
Joe

Reputation: 405

Delete files in current folder that has specific text in filename

I am trying to use a batch script to delete files that has a ( in its name. For example, the file that I would like to delete has the name "Test1 - Copy (5).txt".

I tried this command but it does not work:

for /f "delims=" %%a in (' 
    findstr /l /i /m /c:"(" "C:\Users\Desktop\New folder\*.*"
') do echo del "%%a"

Can you assist me in getting the correct code to delete the files that has a ( in its name? Thanks!

Upvotes: 0

Views: 333

Answers (2)

Mohi Dev
Mohi Dev

Reputation: 3416

You can use this code to remove specific string from file name in any directory

@echo off
setlocal enabledelayedexpansion

rem Set the specific text you want to remove
set "text_to_remove=your_text"

rem Loop through each file in the current directory
for %%F in (*) do (
    set "filename=%%~nF"
    
    rem Remove the specific text from the file name
    set "new_filename=!filename:%text_to_remove%=!"

    rem Rename the file with the modified name
    ren "%%F" "!new_filename!%%~xF"
)

echo Files with specific_text removed from names.
pause

Upvotes: 1

SomethingDark
SomethingDark

Reputation: 14370

Usually when someone online gives you code that could be destructive (like code to delete a bunch of files), they'll preface the delete command with an echo so that you can see what commands would be run. In order to actually run the command, simply remove the echo:

for /f "delims=" %%a in ('findstr /l /i /m /c:"(" "C:\Users\Desktop\New folder\*.*"') do del "%%~a"

However, this is a lot of typing (and it's doing a case-insensitive search for an open parentheses for some reason), so you can simply use wildcards to delete any files whose name contain the string you're looking for:

del "%USERPROFILE%\Desktop\New folder\*(*"

Upvotes: 1

Related Questions