-1

Imagine a text file which contains random text and two unique markers

01 text text text
02 text text text
03 __DELETE_THIS_FIRST__
04 text text text
05 text text text
06 text text text
07 text text text
08 __DELETE_THIS_LINE_SECOND__
09 a few
10 interesting
11 lines follow
12 __DELETE_THIS_LINE_THIRD__
13 text text text
14 text text text
15 text text text
16 text text text
17 __DELETE_THIS_LINE_FIRST__
18 text text text
19 text text text
20 text text text
21 text text text
22 __DELETE_THIS_LINE_SECOND__
23 even
24 more
25 interesting lines
26 __DELETE_THIS_LINE_THIRD__

I want a Python expression that moves the interesting lines between the END marker and thr THIRD marker to the position of the PREVIOUS BEGIN marker and also deletes all three markers. Which should result in:

01 text text text
02 text text text
09 a few
10 interesting
11 lines follow
04 text text text
05 text text text
06 text text text
07 text text text
13 text text text
14 text text text
15 text text text
16 text text text
23 even
24 more
25 interesting lines
18 text text text
19 text text text
20 text text text
21 text text text

The three markers are always a triple and occur multiple times in the file. FIRST marker always occurs before SECOND marker, which always occurs before THIRD marker

Any ideas?

Related: 126325

1 Answer 1

0

Here's a script in Python, that does the job.

#! /usr/bin/env python

buffer = []
markerBuffer = []

beginFound = False
endFound = False

begin_marker = "__DELETE_THIS_LINE_FIRST__"
end_marker = "__DELETE_THIS_LINE_SECOND__"

line_count_marker = "__DELETE_THIS_LINE_THIRD__"

with open('hello.txt') as inFile:
    with open('hello_cleaned.txt', 'w') as outFile:
        for line in inFile:
            if begin_marker in line and delete_marker in line:
                beginFound = True
                continue
            if end_marker in line and delete_marker in line:
                assert beginFound is True
                endFound = True
                continue
            if beginFound and not endFound:
                markerBuffer.append(line)
                continue
            if beginFound and endFound and line_count_marker not in line:
                buffer.append(line)
                continue
            if beginFound and endFound and line_count_marker in line:
                for mLine in markerBuffer:
                    buffer.append(mLine)

                markerBuffer = []
                beginFound = False
                endFound = False
                continue
            if not beginFound and not endFound:
                buffer.append(line)
                continue
        for line in buffer:
            outFile.write(str(line))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.