Search code examples
batch-file

Copy set amount of lines from 1 file to an other file


I have a file that has a couple 100 lines in it. I only want to keep a portion of it, and discard the rest. First I build a function that gives me the row number where the file should really end on by using this:

for /f "tokens=1 delims=:" %%a in ('
findstr /n /c:"(search term)" "(source file location and name)"
') do set start=%%a
SET /A truestart=%start%-1

This gives me a row value that is 1 above the searched term and that is exactly what I want. E.g. the value is 600 so it copies rows 1 to 599 to a different file and ignores row 600 to end document.

I tried looking for a solution thinking I should be using a form of loop to copy the lines 1 by one to a new file until specified line is reached.

I found this loop on this page that supposed to do what I want:

setlocal ENABLEEXTENSIONS
setlocal ENABLEDELAYEDEXPANSION

:: set counter
set c=0
for /f "delims=|" %%i in ("source file location and name") do (
:: increment counter for each line read
  set /a c=!c!+1
  if !c! leq %truestart% echo %%i >> "destination file location and name"
)

This give me a new file, but it copies only the source file location and name to the destination file and not the content in the source.

So I know I am missing something reading out the source per line but I can't figure out what.

I also tried using more:

more /e /p +%truestart% "source file location and name" > "destination file location and name"

This gives me the opposite, this displays only the part what I want to take out and leaves out what I actually want.


Solution

  • Thanks for the suggestions. I cleaned it up a bit based on your suggestions. After a bit of research I found a better workaround.

    I managed to get the result I wanted trough powershell:

    @echo off
    
    rem set final line
    for /f "tokens=1 delims=:" %%a in ('
    findstr /n /c:"(search term)" "(source document)"
    ') do set /a end=%%a-2
    
    set "inputFile="(source document)""
    set "outputFile="(destination document)""
     
    powershell -Command "Get-Content -Path '%inputFile%' -TotalCount %end% | Set-Content -Path '%outputFile%'"
    

    This gives me exactly the result I want.