Deleting last n lines from file using batch file

后端 未结 4 1859
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 09:47

How to delete last n lines from file using batch script

I don\'t have any idea about batch files, I am writing batch file for the first time.

How should I wr

4条回答
  •  天涯浪人
    2020-12-10 10:03

    This the complete script for remove last N line

    • count the total line
    • set Line = Line - N , remain just processing lines number
    @echo OFF
    setlocal EnableDelayedExpansion
    
    set LINES=0
    for /f "delims==" %%I in (infile.txt) do (
        set /a LINES=LINES+1    
    )
    
    echo Total Lines : %LINES%
    echo.
    
    :: n = 5 , last 5 line will ignore 
    set /a LINES=LINES-5
    
    call:PrintFirstNLine > output.txt
    
    goto EOF
    
    :PrintFirstNLine
    set cur=0
    for /f "delims==" %%I in (infile.txt) do (      
        echo %%I        
        ::echo !cur! : %%I      
        set /a cur=cur+1    
        if "!cur!"=="%LINES%" goto EOF
    ) 
    
    :EOF 
    
    exit /b
    

    Here call:PrintFirstNLine > output.txt will give the output in an external file name as output.txt

    Output for sample Input

          
          
                
        D:\CBA\CBA_Notifier\Project_Name\IPS-Util.jar      
        D:\CBA\CBA_Notifier\Project_Name\Notifier.bat      
        D:\CBA\CBA_Notifier\Project_Name\Notifier.xml      
        D:\CBA\CBA_Notifier\Project_Name\Notifier.jar              
               
              
            D:\CBA\CBA_Notifier\IPS-Util.bat   
    

    remove last 5 line

    Update

    :PrintFirstNLine
    set cur=0
    for /F "tokens=1* delims=]" %%I in ('type "infile.txt" ^| find /V /N ""') do (
       if "%%J"=="" (echo.) else (
            echo.%%J
            set /a cur=cur+1    
            )  
    
       if "!cur!"=="%LINES%" goto EOF
    )
    

提交回复
热议问题