Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file to delete first 3 lines of a text file

As the title states I need a batch file to delete the FIRST 3 lines of a text file.

for example:

A    
B    
C    
D    
E   
F    
G

in this example I need A,B and C deleted along with the line

like image 864
kriegy Avatar asked Jul 11 '12 08:07

kriegy


People also ask

How do I create a line break in batch file?

How can you you insert a newline from your batch file output? You can insert an invisible ascii chr(255) on a separate line which will force a blank new line. Hold down the [alt] key and press 255 on the keypad.


2 Answers

more +3 "file.txt" >"file.txt.new"
move /y "file.txt.new" "file.txt" >nul

The above is fast and works great, with the following limitations:

  • TAB characters are converted into a series of spaces.
  • The number of lines to be preserved must be less than ~65535. MORE will hang, (wait for a key press), if the line number is exceeded.
  • All lines will be terminated by carriage return and linefeed, regardless how they were formatted in the source.

The following solution using FOR /F with FINDSTR is more robust, but is much slower. Unlike a simple FOR /F solution, it preserves empty lines. But like all FOR /F solutions, it is limited to a max line length of a bit less than 8191 bytes. Again, all lines will be terminated by carriage return and linefeed.

@echo off
setlocal disableDelayedExpsnsion
>"file.txt.new" (
  for /f "delims=" %%A in ('findstr /n "^" "file.txt"') do (
    set "ln=%%A"
    setlocal enableDelayedExpansion
    echo(!ln:*::=!
    endlocal
  )
)
move /y "file.txt.new" "file.txt" >nul

If you have my handy-dandy JREPL.BAT regex text processing utility, then you could use the following for a very robust and fast solution. This still will terminate all lines with carriage return and linefeed (\r\n), regardless of original format.

jrepl "^" "" /k 0 /exc 1:3 /f "test.txt" /o -

You can write \n line terminators instead of \r\n by adding the /U option.

If you must preserve the original line terminators, then you can use the following variation. This loads the entire source file into a single JScript variable, so the total file size is limited to approximately 1 or 2 gigabytes (I forgot the exact number).

jrepl "(?:.*\n){1,3}([\s\S]*)" "$1" /m /f "test.txt" /o -

Remember that JREPL is a batch file, so you must use CALL JREPL if you use the command within another batch script.

like image 61
dbenham Avatar answered Sep 24 '22 18:09

dbenham


I use "more" command for outting file after nth line Command (windows)

More +n orginalfilename.txt > outputfilename.txt

Description: Outputting file of txt after nth line

like image 27
Sarah Filano Avatar answered Sep 23 '22 18:09

Sarah Filano