Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fold python code using sed and/or awk?

I have a large python code base. I want to get a feel of how a BaseClass is subclassed by ‘grepping-out’ the name of the sub class and the functions in the class, but only for classes that inherit from SomeBaseClass.

So if we have multiple files that have multiple classes, and some of the classes look like:

class SubClass_A(BaseClass):
    def foo(self):
        ...

    async def goo(self):
        ...

class AnotherClass:
    ...

class SubClass_B(BaseClass):
    def foo(self):
        ...

    async def goo(self):
        ...

If we apply some sort of scrip to this code, it would output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

File: /path/to/file
class SubClass_A(BaseClass):
    def foo(self):
    async def goo(self):
class SubClass_B(BaseClass):
    def foo(self):
    async def goo(self):

There can be many classes in the same file some of them may be a BaseClass. Essentially, this is like folding lines of code in an IDE.

Now, I tried using sed to do this, but I’m not an expert in it, and sed won’t be able to print the file path. However, I know awk can print the file path, but I don’t know awk! Argh.

I thought about writing a python program to do this, but this problem seems like something a nifty sed/awk program can do.

Thanks for the help.

>Solution :

Using any awk, this may be what you’re trying to do:

$ awk '/^class/{ f=/\(BaseClass)/ } f && $1 ~ /^(class|def|async)$/' file
class SubClass_A(BaseClass):
    def foo(self):
    async def goo(self):
class SubClass_B(BaseClass):
    def foo(self):
    async def goo(self):
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading