2

Quite nervous today, I am a long time StackOverflow voyeur about to ask my first ever question so I hope I dont suck at it. I can perform the following task easily using something like a console app but i was hoping that it would be possible to do it in a batch script, and I dont know batch scripting well at all.

I want to delete all files in a directory except those whose name matches a certain pattern. A typical example of the kind of files in this directory is as follows:

  • dep_invoice_101.pdf -- to delete
  • dep_invoice_102.pdf -- to delete
  • invoice_103.pdf -- to delete
  • invoice_106.pdf -- to delete
  • invoice_106_E56.pdf -- keep
  • deposit_invoice_101_068.pdf -- keep

i want to delete all files except those whose name matches

  • any string (or nothing) followed by "invoice_"
  • followed by any number
  • then an underscore
  • then another alphanumeric string

The final underscore is the key. if i was doing this using C# or something, i would extract the name into a string, remove all text before "invoice_" and then see if there is a remaining underscore - this would be a match, e.g.

  • "deposit_invoice_101_068.pdf"
  • search for "invoice_" and remove all text before and including this
  • left with "101_068.pdf"
  • if there are any underscores in this string then it is a match

Hope this makes sense. If this is not an appropriate question let me know.

Many thanks

2 Answers 2

2
for /f "tokens=*" %%a in (
  'dir /a-d /b *.pdf ^| findstr /v /r /c:"invoice_[0-9][0-9]*_.*\.pdf$"'
) do echo del "%%a"

If output to console is correct, remove the echo command

Sign up to request clarification or add additional context in comments.

Comments

1
@ECHO Off
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
FOR /f "delims=" %%a IN (
  'dir /b /a-d "%sourcedir%\*" '
  ) DO (
 SET "filename=%%a"
 SET "filename=!filename:*invoice_=!"
 IF "!filename!"=="!filename:_=!" ECHO DEL "%sourcedir%\%%a"
)

GOTO :EOF

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.

You'd need to change your sourcedir to suit, naturally.

This follows your how I'd do it in C rather than your narrative spec.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.