35

In a Windows batch-file, this line:

del *.txt

Will give the error/warning message:

Could Not Find C:\*.txt

if there are no files matching the pattern *.txt. Is there a way to prevent that message?

4 Answers4

44
if exist *.txt del *.txt
peterchen
  • 40,917
  • 20
  • 104
  • 186
36

If you want to suppress all error messages, you can do this:

del *.txt 2>NUL
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • 1
    What is that `2`? Why `del *.txt >NUL` doesn't work? – nrofis Dec 08 '15 at 13:56
  • 1
    @nrofis: It redirects the error output, rather than the standard output. See https://en.wikipedia.org/wiki/Standard_streams for the numbering. – RichieHindle Dec 09 '15 at 08:18
  • 3
    The disadvantage of this method is that if there is a real error, such as the files are locked then that message will be swallowed. Personally, I prefer @peterchen's if exist approach. – Lee Oades Jan 18 '18 at 08:47
4

surround with an if exists...

or use a different delete utility {like 'rm' from the mks tools}

or take a look at forfiles.exe - that should do what you need.

phatmanace
  • 4,671
  • 3
  • 24
  • 29
-1

Create one.

echo "Moo" > temporary-del-workaround.txt

Your removed file count will be off-by-one though.

edit:

  • NUL redirect answer is wrong because there can be real errors.
  • exists answer is suboptimal because it does the work twice and if you've filled your directory with 60K+ files, the simple listing will easily be as long as removal
Pasi Savolainen
  • 2,460
  • 1
  • 22
  • 35