Reputation: 159
How do you all delete the newest file in a folder using batch script?
All results I have found ONLY show how to delete the oldest files or delete them after N days.
Links are : Batch file to delete files older than N days and Batch Script to delete oldest folder in a given folder
Thank you
Upvotes: 1
Views: 2257
Reputation: 34899
The following code snippet does what you want:
set "FILE="
pushd "\path\to\folder" || exit /B 1
for /F "eol=| delims=" %%F in ('
dir /B /A:-D /O:D /T:C "*.*"
') do (
set "FILE=%%F"
)
if defined FILE del "%FILE%"
popd
The dir
command returns files only (/A:-D
) sorted by date in ascending order (/O:D
) using the creation date (/T:C
), which are located in \path\to\folder
and match the pattern *.*
.
The for /F
loop walks through all the files returned by dir
and assigns its name to variable FILE
, overwriting it in each iteration, hence the final value is the name of the newest file.
The del
command finally deletes the found file. The if
query covers the case when no files are found in the given location.
Here is a slightly modified variant as recommended by Magoo's comment, which might be a bit more performant than the aforementioned one:
set "FILE="
pushd "\path\to\folder" || exit /B 1
for /F "eol=| delims=" %%F in ('
dir /B /A:-D /O:-D /T:C "*.*"
') do (
if not defined FILE set "FILE=%%F"
)
if defined FILE del "%FILE%"
popd
This avoids multiplicately overwriting of variable FILE
by querying whether it has already been defined. Note the reversed sort order of dir
here.
However, the approach shown in Magoo's answer is still better in performance.
Upvotes: 1
Reputation: 79983
for /F %%a in ('dir /B /O-D /A-D %the_directory%') do echo("%the_directory%\%%a"&goto deldone
:deldone
would be my approach. It rudely escapes from the for
loop having deleted the first filename encountered in a sorted-in-reverse-date-order (/o-d
) list.
This saves having to read the entire list. Not such a problem with a few files, but can be a pain with thousands.
The required DEL command is merely ECHO
ed for testing purposes. After you've verified that the command is correct, change ECHO(DEL
to DEL
to actually delete the files.
Upvotes: 2
Reputation: 140168
I would do this:
@echo off
set latest=
set the_directory=your_directory
for /F %%a in ('dir /B /OD /A-D %the_directory%') do set latest=%%a
del %the_directory%\%latest%
run dir
on files only, with sorting on modification date. Then loop and keep last echoed file. Delete it (replace by echo
to test!)
Upvotes: 1