mgk
mgk

Reputation: 31

How to remove files containing string in specific place?

How do I remove files, which have a specific string in a specific place in their filename, using a batch file?

I want to remove files containig specific strings, entered by the end user.

For example, I want to remove all files containing 2019 from several directories where the filename looks like this:

FILE 2019.03.09.FILE.2019.XXX

I have this code for this:

@ECHO off
TITLE REMOVE FILES
@ECHO:
SET /p _FileNumber= Enter file number You want to remove:

del /q /s "C:\Directory1\*%_FileNumber%.*"
del /q /s "C:\Directory2\*%_FileNumber%.*"

PAUSE

I enter specific number and it works, but also removes all files that have a Year in name.

Can I add something that will take variable from number before extension field?

Upvotes: 2

Views: 267

Answers (2)

double-beep
double-beep

Reputation: 5504

If all the files you provided are in the format FILE yyyy.mm.dd.FILE.yyyy.ext, then use findstr with regular expressions:

@echo off
title REMOVE FILES
echo:
set /p "_FileNumber=Enter file number You want to remove: "

for /F "delims= eol=" %%A IN ('dir /S /B /A-D "*" ^| findstr /RC:"FILE %_FileNumber%\.[0-9][0-9]\.[0-9][0-9]\.FILE\.%_FileNumber%\.ext"') do del /F /A "%%~fA"

pause

This, will delete for sure all files containing user input in the format you mentioned.

Regular expression explanation:

  • /R enables it in findstr
  • \ is an escape character
  • . is a wildcard; it means any character, so it is escaped with \ as you want a real dot.
  • [0-9] means to match only if one of the characters in [] exist so, if any of the characters 1, 2, 3, 4, 5, 6, 7, 8, 9 exist.

For more information about the commands used, please type in cmd.exe:

  • for /?
  • set /?
  • title /?
  • echo /?
  • findstr /? explains regular expressions accepted
  • pause /?
  • dir /?
  • del /?

Upvotes: 1

mgk
mgk

Reputation: 31

Thank You for all Your answers and comments. I solved the issue in other way. I simply added a dot before percentage sign, and removed the one at the end. Since there isn't one before date it solves the problem. Works fine - tested with about 50 different file names combinations.

del /q /s "C:\Directory1\*.%_FileNumber%*"
del /q /s "C:\Directory2\*.%_FileNumber%*"

Upvotes: 1

Related Questions