Batch file that keeps the 7 latest files in a folder

拜拜、爱过 提交于 2019-11-28 21:26:41

You can use DIR with /O-D to list the text files in descending timestamp order. FOR /F allows you to iterate over each file. SET /A is used to keep track of how many files have been listed so far. Now comes the tricky part.

Within a code block you normally need to use delayed expansion to work with the value of a variable that was set earlier in the same block. But delayed expansion can cause problems in a FOR loop if the FOR variable value contains !, and ! is valid in file names. I get around the problem by using SET /A to intentionally divide by 0 when the 7th file name has been read. This raises an error that causes the conditional code to execute that undefines the KEEP variable. From that point on, all remaining files are deleted.

@echo off
setlocal
set /a cnt=0
set "keep=7"
for /f "eol=: delims=" %%F in ('dir /b /o-d /a-d *.txt') do (
  if defined keep (
    2>nul set /a "cnt+=1, 1/(keep-cnt)" || set "keep="
  ) else del "%%F"
)

Update

Oh my goodness, I just realized there is a trivial solution. Just use the FOR /F SKIP option to ignore the first 7 entries after sorting by last modified date, descending.

for /f "skip=7 eol=: delims=" %%F in ('dir /b /o-d /a-d *.txt') do @del "%%F"

You don't even need a batch file. Just change %% to % if run from the command prompt.

The Batch file below use a simpler approach. It use findstr /N "^" command to number each file, then it just compare each number to keep first seven files and delete the rest...

@echo off
for /f "tokens=1* delims=:" %%a in ('dir /b /o-d *.txt ^| findstr /N "^"') do (
   if %%a gtr 7 del "%%b"
)

Antonio

Sarang A

This will keep 7 latest .txt files and remove all other .txt files

Execute below command in same directory from which you want to delete files

On command prompt

for /f "skip=7 eol=: delims=" %F in ('dir /b /o-d /a-d *.txt') do @del "%F"

Inside batch script

for /f "skip=7 eol=: delims=" %%F in ('dir /b /o-d /a-d *.txt') do @del "%%F"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!