Search code examples
batch-filecmddelete-fileskip

How to skip number of lines that changed in run time in cmd?


I have many folders and i need to delete from any folder the oldest files in it, the number of files that i need to delete changed any iteration so i tried to do a for loop that in any iteration do date sort, after the oldest file at the top of the file i do "skip=variable" this variable changed any iteration and it's not work.

Is someone have any idea how to solve it in batch file? Thanks!


Solution

  • The options of for /F command ("skip... delims... tokens", etc) can not be changed after the for /F command was parsed. You need to change the value of "skip=!numOfFiles!" in a different subroutine, so the for /F command be parsed each time it is executed:

    @echo off
    setlocal EnableDelayedExpansion
    
    FOR /F "tokens=1,2 delims= " %%i in ( C:\folder\varibales_file.txt ) do (
       set numOfFiles=%%j
       pushd %%i
       call :Sub !numOfFiles!
       popd
    )
    goto :EOF
    
    
    :Sub numOfFiles
    for /f "skip=%1 delims=" %%F in ('dir "C:\folder_path_to_delete\%%i" /b /o-d') do (
       rd /s /q "C:\folder_path_to_delete\%%i\%%F"
    )