0

Can anyone provide a windows command or batch script that will remove the top two rows from a text file?

I'd like to remove the first two lines of a text file using findstr. I can't use the "more +2 file.txt > newfile.txt" trick described here because i'm calling this via xp_cmdshell and that doesn't seem to work (process often hangs and creates a permanently locked file I can't delete).

I've heard that findstr can use regular expressions to find something like this, and i've seen some attempts using a bat file. I'm open to either one of these possibilities but haven't found a working solution yet.

Community
  • 1
  • 1
FistOfFury
  • 6,735
  • 7
  • 49
  • 57

1 Answers1

2

try this:

@echo off &setlocal
set "myfile=%~1"
(for /f "delims=" %%i in ('findstr /n "^" "%myfile%"') do (
    set "line=%%i"
    for /f "delims=:" %%a in ("%%i") do set "row=%%a"
    setlocal enabledelayedexpansion
    set "line=!line:*:=!"
    if !row! gtr 2 echo(!line!
    endlocal
))>newfile
type newfile

btw. syntax for more:

<file>newfile more +2
Endoro
  • 37,015
  • 8
  • 50
  • 63
  • 1) replace the word `file` after `findstr` with the name of your file. 2) I made an edit, added `>` before `newfile`. – Endoro Jun 10 '13 at 21:25
  • pretty cool! Is it possible to pass in a file name as an argument? – FistOfFury Jun 10 '13 at 21:28
  • it mostly works when i type my filename into the batch. I have to delete newfile each time or the results get appended again. IS it possible to pass in a filename when i run the batch instead? e.g. "EndoroBatch.bat myfile.txt"? – FistOfFury Jun 10 '13 at 21:32
  • 1
    Yes, now you can use your file name as parameter and the `newfile` will be always overwritten. – Endoro Jun 10 '13 at 21:37