Search code examples
windowsbatch-filefindstr

Getting texts between two words in a text file


for brevity sake, I have a text file (in windows) that looks like this:

Blah Blah Blah Blah
Blah Blah Blah 2016
START-OF-FILE
ABC
ABCDE Blah Blah Blah
Blah Blah Blah Blah
Blah Blah Blah Blah Blah Blah
END-OF-FILE
Blah Blah Blah
Blah Blah Blah

I only want the text between START-OF-FILE and END-OF-FILE

ABC
ABCDE Blah Blah Blah
Blah Blah Blah Blah
Blah Blah Blah Blah Blah Blah

I tried using Findstr, but not working too well. Can someone help?

here is what I have so far:

@echo off
setlocal enabledelayedexpansion

set quote=

for /f "tokens=*" %%a in (infile.txt) do (
  set str=%%a
  set str=!str:"=:!

  if not "!str!"=="!str::=!" (
    if defined quote (
      set quote=
      for %%b in (^"%%a) do set str=%%~b
      if not "!str!"==START-OF-FILE if not "!str: =!"==END-OF-FILE echo !str! >> outfile.txt
    ) else (
      set quote=1
      for %%b in (%%a^") do set str=%%~b
    )
  )

  if defined quote (
    if not "!str!"==START-OF-FILE if not "!str: =!"==END-OF-FILE echo !str! >> outfile.txt
  )
)

and this is the result:

2016" 
START-OF-FILE 
ABC
ABCDE Blah Blah Blah
Blah Blah Blah Blah
Blah Blah Blah Blah Blah Blah
END-OF-FILE
Blah Blah Blah

I need the 2016" ,START-OF-FILE ,END-OF-FILE and line after END-OF-FILE (Blah Blah Blah) to not be included


Solution

  • @echo off
    setlocal EnableDelayedExpansion
    
    set "skip="
    for /F "delims=:" %%a in ('findstr /N "START-OF-FILE END-OF-FILE" input.txt') do (
       if not defined skip (
          set "skip=%%a"
       ) else (
          set /A "lines=%%a-skip-1"
       )
    )
    (for /F "skip=%skip% delims=" %%a in (input.txt) do (
       echo %%a
       set /A lines-=1
       if !lines! equ 0 goto break
    )) > output.txt
    :break