Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

windows 7 - Deleting last n lines from file using batch file

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 write this batch file?

For Windows7

Try it for

<Project_Name>

    <Noter>
        <Common>
        <File>D:Project_NameUtil.jar</File>
        <File>D:Project_NameNoter.bat</File>
        <File>D:Project_NameNoter.xml</File>
        <File>D:Project_NameNoter.jar</File>       
        </Common>

        <Project_Name>
            <File>D:Util.bat</File>
            <File>D:Util.xml</File>
            <File>D:log.bat</File>
        </Project_Name>
    </Noter>
    <CCNET>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

<Project_Name>      
<CBA_Notifier>      
    <Common>        
    <File>D:CBACBA_NotifierProject_NameIPS-Util.jar</File>      
    <File>D:CBACBA_NotifierProject_NameNotifier.bat</File>      
    <File>D:CBACBA_NotifierProject_NameNotifier.xml</File>      
    <File>D:CBACBA_NotifierProject_NameNotifier.jar</File>              
    </Common>       
    <Project_Name>      
        <File>D:CBACBA_NotifierIPS-Util.bat</File>   

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
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...