0

I am trying to write a batch file that will examine a given directory, read each file for a given string "Example" and then delete any files that contain the string. The files are also System Files so I don't know what the exact extension is or if that matters (maybe you can just omit a file type filter and have it read all files?). Some of the files will be locked from reading as well so it needs to handle access denial errors if that occurs, not sure how batch files handle that.

Update What I ended up using was this:

for /f "eol=: delims=" %F in ('findstr /m monkey *.txt') do del "%F"

Found here: Search and then delete depending on whether files contain a string

I ended up finding it shortly after I posted this.

Community
  • 1
  • 1
Fuzz Evans
  • 2,893
  • 11
  • 44
  • 63

1 Answers1

1

Try something like this:

@echo off

cd "C:\some\where"
for /f %%f in ('dir /b /a:-d *') do (
  findstr "Example" "%%~ff" && (
    attrib -r -s -h "%%~ff"
    del /q "%%~ff"
  )
)
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • I had to add a 'cd' prior to your command to have the active directory match the directory in the command, otherwise it seems to find files in the intended directory, then look for them on my desktop (my active directory?). When I use the CD call first, I get results in my output where it identifies the files that contain "example" but the file doesn't get deleted. I get a message at the end indicating 'access is denied'. I'm wondering if the stream is still open when the delete command is called? – Fuzz Evans Jul 01 '13 at 23:24
  • Could be that the file is still opened by a process (you can check that with Sysinternals' [`handle`](http://technet.microsoft.com/en-us/sysinternals/bb896655) utility), or you don't have sufficient permissions for deleting the file. You can use [`icacls`](http://technet.microsoft.com/en-us/library/cc753525) to verify/adjust permissions and ownership of the files. – Ansgar Wiechers Jul 01 '13 at 23:33