Skip to content
Advertisement

Extract blocks of text that starts with “Start Text” until it encounters another “Start Text”

Here is the code I have to extract blocks of text of a file that starts with “Start Text” until it encounters another “Start Text”.

JavaScript

INPUT: “temp.txt” has the following structure:

JavaScript

DESIRED OUTPUT: I am trying to create multiple text files below with extracted blocks of texts.

file1.txt

JavaScript

file2.txt

JavaScript

file3.txt

JavaScript

UNDESIRED OUTPUT (What the code produces)

file1.txt

JavaScript

file2.txt

JavaScript

file3.txt

JavaScript

Here is the issue I am facing. The code creates three files but does not write “Start Text” lines into their respective text blocks. I am not sure what I am missing. I will appreciate any pointers.

Advertisement

Answer

When the code sees “Start Text” in a line, it writes that line and all the previous lines to the output file.

This explains why the first output file contains only the header — that is the first line in the input file, so obviously there aren’t any previous lines.

It seems like what you really want is for the header and the following lines to be written.

I’ve updated your code to not write a file after seeing the very first header, and also to write a file after the input file is exhausted.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement