python-scan-text-block-reverse

python-scan-text-block-reverse

example finding a block.

start string and reverse search up to next string. then replacing a line inside the block

python example

#!/usr/bin/python
import re
import sys

#v0.9.6
fileName="listener_test.yml"
dir="./unregister"
variable="bar"
block_start='CodeUri: ' + dir
block_end='AWS::Serverless::Function'
rtext = '      AutoPublishCodeSha256: ' + variable + '\n'

with open("listener_test.yml") as ofile:
      lines=ofile.readlines()
      i = len(lines) - 1
      AWSFound = False
      CodeUriFound = False
      AutoFound = False
      unum = 0
      while i >= 0 and not AWSFound:
           if block_start in lines[i]:
             CodeUriFound = True
             unum = i
           if "AutoPublishCodeSha256:" in lines[i]:
             AutoFound = True
             unum = i
           if block_end in lines[i] and CodeUriFound:
             AWSFound = True

           i -= 1

if AutoFound:
  lines[unum] = rtext
else:
  lines.insert(unum - 1, rtext)

with open('listener_test_new.yml', 'w') as file:
  lines = "".join(lines)
  file.write(lines)