# Solved: Batch file to del *.txt files from a dir older than today



## odewallrus (Feb 23, 2009)

I thought this would easy to find, but so far I have been unsuccessful.

I am looking for a batch file that will delete all .txt files except ones with the current days modified date from a specified directory if anyone can assist?


----------



## Squashman (Apr 4, 2003)

Would probably be easiest to do this with Forfiles. You can probably get it from one of the resource kits.


```
forfiles /p c:\backup /s /m *.* /d t-1 /c "cmd /c del @file"
```


----------



## devil_himself (Apr 7, 2007)

delete all files whose dates are not equal to today's date'.


```
@echo off
setlocal
set srcdir="c:\test"
pushd "%srcdir%"
for /f "tokens=2" %%a in ('date /t') do set today=%%a
for /f "tokens=1,5" %%a in ('dir /a-d *.txt ^| find "/"') do if not "%%a"=="%today%" echo del "%%b"
```


----------



## odewallrus (Feb 23, 2009)

devil_himself,

Any code to deal with filenames that contain spaces?


----------



## devil_himself (Apr 7, 2007)

```
@echo off
setlocal
set srcdir="c:\test"
pushd "%srcdir%"
for /f "tokens=2" %%a in ('date /t') do set today=%%a
for /f "tokens=1,4*" %%a in ('dir /a-d *.txt ^| find "/"') do if not "%%a"=="%today%" echo del "%%c"
```


----------



## odewallrus (Feb 23, 2009)

devil_himself,

That works great. Thank you for the assistance.


----------



## Squashman (Apr 4, 2003)

I think I would have opted for one line of code.
But there is always 2 ways to skin a cat.


----------



## odewallrus (Feb 23, 2009)

Actually, I tried FORFILES. Not only would I have to push this to multiple clients along with the script, but I was unable to get it to work correctly. I didn't mean to hurt any feelings. I do appreciate your assistance as well and did entertain that option first.


----------



## Squashman (Apr 4, 2003)

odewallrus said:


> Actually, I tried FORFILES. Not only would I have to push this to multiple clients along with the script, but I was unable to get it to work correctly. I didnt mean to hurt any feelings. I do appreciate your assistance as well and did entertain that option first.


Depending on which version of forfiles you have it may have different syntax. So you are probably better off with the batch file. I assumed you were running a server and would be implementing this yourself.


----------

