views:

138

answers:

4

Hi All,

I'm trying to write a small batch script that will delete files old files from a directory. The first parameter is the directory for the script to look into, and the second is the number of files to preserve.

rem @ECHO OFF

rem %1 is the path in which to look for the files
rem %2 is the number of recent files to preserve

if [%1] EQU [] (
    echo ERROR: Missing Required Paramater directory path.
    goto :eof
)

if [%2] EQU [] (
    echo ERROR: Missing Required Paramater, number of files to preserve
    goto :eof
)

if %2 LSS 0 (
    echo ERROR: Number of files to preserve provided was negative
    goto :eof
)

set FolderPath=%1
set SafeNumber=%2

cd %FolderPath%

for /f %%f in ('dir /O-D /A-D /B') do call :delete %%f
goto :eof

:delete
if %SafeNumber% LEQ 0 (
    del %1
) else (
    set /a SafeNumber-=1
)
goto :eof

:eof

Essentially what I have here is a dir that outputs a list of filenames ordered from newest to oldest. Depending on what SafeNumber is, it will skip the first few files and then procede with deletion once SafeNumber <= 0.

The problem I'm having right now, is if the filename is "Test File.txt" (as in contains a space. "Test" is passed into the delete as %1, rather then "Test File.txt".

Any ideas on how to get my script working, or perhaps someone has a better written solution?

+2  A: 

Have you tried putting quotation marks around the file name in your input, or in your script? I mean around the %f or the %1, for the script.

Mark Rushakoff
Changed the for statement to be:for /F "delims=" %%f in ('dir /O-D /A-D /B %FolderPath%') do call :delete "%%f"and now the delete gets the full filename. Quotations helped a bunch, didn't think of that thanks.
Denis Sadowski
A: 

To handle whitespace in filenames,etc. You'll want to quote for filenames and paths "%1" etc.... Maybe that is your only problem.

kenny
A: 

your going to have to use the find command with -newer and then -exec rm. For example to delete all file newer than file.txt do:

find . -type f -newer file.txt -exec rm {} \;
ennuikiller
He is asking a question about DOS/Win batch files, not Unix shell!
Pavel Minaev
give cygwin a try
ennuikiller
the unix find command has been ported to Windows. for the above , it will be-> find c:\path -type f -newer file.txt -delete
ghostdog74
thanks ghostdog! I guess someone should remove the -1 please?
ennuikiller
A: 

Long time ago, I wrote a simple Java prog that is supposed to be launched from the console, i.e. from a batch file. The prog deletes the old files from a specified directory. Check it out here, I actually don't remember how exactly it works, but I would suggest using it first on a test-folder. It is supposed to be used for Windows, at least there it is where I used it.

I now switched to a Mac, where I'm using the following Automator script I launch on each boot for doing that job:

find /Users/<yourUser>/Downloads/* -type f -mtime +90 -exec mv -f {} /Users/<yourUser>/.Trash \;
Juri