Skip to content
wordpress meta

title: python-scan-text-block-reverse
date: '2020-04-12T08:48:23-05:00'
status: publish
permalink: /python-scan-text-block-reverse
author: admin
excerpt: ''
type: post
id: 1576
category:
    - Python
tag: []
post_format: []

example finding a block.

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

python example

```python

!/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)

````