I have a question regarding deleting the oldest file after a folder gets an X amount of files with the same extension, in this case, all the files share in common the extension *.bak, they are small files that I create for my firefox RES, they have imprinted on the title, the date and hour of creation, and that's as far as I can go.
Anyways, I've stumbled across this: Batch Script to delete oldest folder in a given folder. And I'm struggling to get it to work on my idea.
The thing is that I want the batch to simply check which file is the oldest after it creates a new one using this simple line of code.
copy /y store.json "%DROPBOX%\RES BACKUPS\store.json %date:~-4,4%-%date:~-7,2%-%date:~-10,2%_%time:~0,2%hs-%time:~3,2%min-%time:~6,2%s.bak"
You can use this:
#echo off
for /f "delims=" %%a in ('dir /b /a-d /t:w /o:d "%DROPBOX%\RES BACKUPS\*.bak"') do (
del "%%a"
goto :breakLoop
)
:breakLoop
I suggest first testing it with echo del "%%a" to make sure it deletes the right file.
This works by getting the output of the dir command, which shows all files in bare format (only filenames, not sizes etc.) sorted by oldest files first. It then deletes the first file found, and breaks the loop.
A version that keeps deleting files while there are more than a specific amount:
#echo off
set "source=%DROPBOX%\RES BACKUPS\*.bak"
set "minFiles=5"
for /f %%A in ('dir "%source%" /a-d-s-h /b ^| find /v /c ""') do if %%A leq %minFiles% goto :eof
:loop
for /f "delims=" %%a in ('dir /b /a-d /t:w /o:d "%source%"') do (
del "%%a"
goto :breakLoop
)
:breakLoop
for /f %%A in ('dir "%source%" /a-d-s-h /b ^| find /v /c ""') do if %%A gtr %minFiles% goto :loop
pause
You can make this non-looping (but still only delete if there are more than 5) by removing the line for /f %%A in ('dir "%source%" /a-d-s-h /b ^| find /v /c ""') do if %%A gtr %minFiles% goto :loop
Related
I am pretty new at programming in batch files, and stack overflow users have being a lot of help. My problem is almost solved. Now there is only one thing that is missing to make my script work is.
for /f "tokens=1,* delims=: " %%i in ('type "C:\dev\1597\AssayInfo.txt" ^| findstr /i CouID') do set "number=%%j"
echo %number%
in this part of the code i need to be able to find the AssayInfo.txt without the folder 1597. In my case i will have a lot of folders with random generated numbers and all of them have a Assayinfo.txt, but if i try to run the code without the 1597 path it just say that could not find the file.
We kind of went through these already, but anyway:
To actually set it as a variable after file was found.:
#echo off
setlocal enabledelayedexpansion
for /f %%i in ('dir /s /b /a-d AssayInfo.txt') do (
for /f "tokens=2" %%a in ('type "%%~fi" ^| findstr /i "CouID"') do set "number=%%a"
echo Found number !number! in file "%%~fi"
)
I am new to batch scripting . I need to delete all files in a folder that DOES NOT contains some word in the file
found this code
#echo off
setlocal
pushd C:\Users\admin\Desktop\bat
findstr /ip /c:"importantWord" *.txt > results.txt
popd
endlocal
So how i can WHITE list this files, and delete all other?
Or i think there is easy way with just check if !contains and delete
but i don`t know how?
Supposedly, this problem could be solved in a very simple way combining these findstr switches: /V that show results when the search string is not found, and /M that show just the name of the files; that is:
#echo off
setlocal
cd C:\Users\admin\Desktop\bat
for /F "delims=" %%a in ('findstr /ipvm /c:"importantWord" *.txt') do del "%%a"
Unfortunately, the combination of /V and /M switches don't properly work: the result of /V is based on lines (not files), so a modification in the method is needed:
#echo off
setlocal
cd C:\Users\admin\Desktop\bat
rem Create an array with all files
for %%a in (*.txt) do set "file[%%a]=1"
rem Remove files to preserve from the array
for /F "delims=" %%a in ('findstr /ipm /c:"importantWord" *.txt') do set "file[%%a]="
rem Delete remaining files
for /F "tokens=2 delims=[]" %%a in ('set file[') do del "%%a"
This method is efficient, particularly with big files, because findstr command report just the name of the files and stop searching after the first string match.
#echo off
setlocal
set "targetdir=C:\Users\admin\Desktop\bat"
pushd %targetdir%
for /f "delims=" %%a in ('dir /b /a-d *.txt') do (
findstr /i /p /v /c:"importantWord" "%%a" >nul
if not errorlevel 1 echo del "%%a"
)
popd
endlocal
Not really sure what you want to do with /pfiles - files containing non-ansi characters appear to return errorlevel 1for these. if not errorlevel 1 will echo the files that do not contain the required string - remove the echo to actually delete the file(s)
This should work:
#ECHO OFF
SETLOCAL EnableDelayedExpansion
SET "pathToFolder=C:\FolderToEmpty"
SET "wordToSearch=ImportantWord"
FOR /F "tokens=*" %%F IN ('dir %pathToFolder% /b *.txt') DO (
findstr /IP %wordToSearch% "%pathToFolder%\%%F">nul
IF !ERRORLEVEL!==1 (
DEL /Q "%pathToFolder%\%%F"
)
)
You will have to set the proper path to the folder you want to delete the files from and to replace ImportantWord with the substring you are looking for.
I have a directory that has a 10 sub-directories. Each of these holds different .bak files. I'm trying to create a script that will check to see if X number of files are there and if the number of files exceeds X, it deletes the oldest file. In other words, I want 20 iterations of a .bak file. When the 21st one shows up, I want the batch file to delete the oldest one.
Is this possible?
If so, can I create a single script that looks in all the sub-directories?
Thanks in advance.
Two options included. The first one will leave %maxFiles% bak files under each of the folders. The second one (windows Vista or later OS is required as robocopy is used to obtain the sorted list of files) will leave %maxFiles% in total
#echo off
setlocal enableextensions disabledelayedexpansion
set "rootFolder=%cd%"
set "maxFiles=20"
rem Option 1 - Keep %maxFiles% inside each of the subfolders
for /d /r "%rootFolder%" %%z in (*) do for /f "skip=%maxFiles% delims=" %%a in (
'dir /tc /o-d /a-d /b "%%~fz\*.bak" 2^>nul'
) do echo del "%%~fz\%%~nxa"
echo ------------------------------
rem Option 2 - Keep %maxFiles% in total under all the subfolders
for /f "skip=%maxFiles% tokens=2,*" %%a in ('
robocopy "%rootFolder%" "%rootFolder%" *.bak /l /nocopy /is /s /njh /njs /ndl /nc /ns /ts
^| findstr /v /r /e /i /c:"%rootFolder:\=\\%\\[^\\]*"
^| sort /r
') do echo del "%%b"
del commands are only echoed to console. If the output is correct, remove the echo command to remove the files
assumes that you want to check the number of files from the parent directory.Can be done also for each sub-directory.
#echo off
setlocal
set "max_number_files=20"
set "parrent_dir=c:\whatever_you_need"
set "extension=.bak"
pushd "%parrent_dir%"
set "count=0"
setlocal enableDelayedExpansion
for /f "delims=" %%a in ('dir /s /b /a:-d /o:-d /t:c *%extension%') do (
set /a count=count+1
if 1!count! GTR 1!max_number_files! (
rem --- remove the echo to activate deletion
echo del /q /f "%%~a"
)
)
popd
endlocal
endlocal
This will check each folder under d:\base\folder and if there are more than 20 *.bak files it will remove the oldest ones so only 20 *.bak file remain, in each folder.
Test it on some sample folders.
#echo off
for /d /r "d:\base\folder" %%a in (*) do (
pushd "%%a"
for /f "skip=20 delims=" %%b in ('dir /b /a-d /o:-d *.bak ') do del "%%b"
popd
)
I'm triying to get a list of files of subfolders in a inverse order using this:
for /f "tokens=*" %%f in ('dir /s /b /o-n') do (echo %%f)
I'm getting this result
folder1\file2, folder1\file, folder2\file2, folder2\file1, folder3\file2, folder3\file1
And I want to get the reverse order in folders and files, not only files of folders. Something like this
folder3\file2, folder3\file1, folder2\file2, folder2\file1\, folder1\file2, folder1\file1
How can I do this?
#echo off
for /f "tokens=*" %%f in ('dir /s /b /o-n') do (echo %%f >> tempfile.123)
C:\Windows\System32\sort.exe /R tempfile.123
del tempfile.123
This just echoes your files to tempporary file and then revereses it. Sorry for the full path to sort.exe but I have cygwin installed. In case you want proper temporary file name I reccomend this http://unserializableone.blogspot.com/2009/04/create-unique-temp-filename-with-batch.html
try this
for /f "tokens=*" %%f in ('dir /s /b /o-n')
do (
SET OUTPUT=%OUTPUT%, %%f
)
echo %OUTPUT%
run a first loop to get first level subdir then run you command on each of them
#echo off
for /f "tokens=*" %%f in ('dir c:\temp\so\ /b /o-n /AD') do (call :filesOf %%f)
:next
echo next
pause
:filesOf
echo "files for ******** %1 *********"
if ("%1"=="") goto next else(
for /f "tokens=*" %%i in ('dir c:\temp\so\%1 /s /b /o-n ') do echo "***%%i***"
)
it will be difficult to handle multi level subdirs tough
Can anyone help me create a batch file? Basically, my goal is to create a batch file that will keep the LATEST 7 .txt files (in other words, the newest) in the folder and subsequently delete the rest. That's IF there are more than 7 files in the folder.
The problem I'm having right now is the fact that the batch file that I have created deletes most of the files because their date is from a month or two or so. I want to keep the latest 7 files at all times no matter how old they are.
So this is what I have -
#echo off
setlocal enableextensions
rem ********************************************************************************
rem ******************************* LOCAL VARIABLES ******************************
rem ********************************************************************************
SET TargetDirectory="C:\TEMP\test"
SET No_of_fles_to_keep=7
SET count=0
set cnt=0
rem ********************************************************************************
cd /d %TargetDirectory%
REM timeout /T 500
for %%x in (*) do set /a count+=1
for %%A in (*.bat) do set /a cnt+=1
cd /d %TargetDirectory%
REM timeout /T 500
IF %count% gtr %No_of_fles_to_keep% forfiles -p %TargetDirectory% -s -m "*.txt" -d -%No_of_fles_to_keep% -c "cmd /c del #path"
echo %count%
echo File count = %cnt%
Any help is appreciated.
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
If you don't write DOS scripts frequently which I don't, here is a summation of what others noted.
Other examples here will need the batch file in the same folder that you're deleting from.
To delete from another path: (Notice you have to add the path twice to the search and to the delete)
SET targetDir="C:\Test\Files\"
for /f "skip=7 eol=: delims=" %%F in ('dir /b /o-d /a-d %targetDir%*.txt') do #del "%targetDir%""%%F"
Thanks #dbenham, #SmileyFace, #user2924127 and all others who helped bring the answers.
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"