A smarter 'grep' for python code: want to find nesting function or class
Asked Answered
P

2

0

I am searching a python script for a string, but I would like to see not just the lines that contain the string, but also if that code is nested inside a function or method (or, optionally, a loop or conditional), I would like to see the lines where that function/method/etc. is 'declared' (not sure if that's the right terminology...)

I just mean, when I'm looking for STRING in a file like this:

class my_class(stuff):
     some lines of code
     line of code containing STRING

I'd like it to return:

class my_class(stuff):
     line of code containing STRING

Instead of just:

     line of code containing STRING

It doesn't have to be done with grep, specifically.

Phallus answered 10/11, 2014 at 3:20 Comment(0)
A
2

Nice answer from nullpointer, but a slight modification to limit this to just class or function definitions (rather than including if/lambda/etc) and only using grep...

grep -rE "^\s*def.*:$|STRING" some-directory/ | grep "STRING" -B 1

or

grep -rE "^\s*class.*:$|STRING" some-directory/ | grep "STRING" -B 1

This works for my purposes, but you can modify the -B argument to suit your needs if you're dealing with nested things or if STRING repeats in a given fn/class. The second grep basically ensures STRING is present and that the last match from the first grep is shown, which could be STRING again... in that case you might adjust -B.

Asarum answered 28/4, 2017 at 18:19 Comment(0)
F
0

Using grep

$ grep -E ':$|STRING' input
    class my_class(stuff):
         line of code containing STRING

What it does

  • /:$|STRING/ regex matches : at the end of line $ as in class def or any control structure in python. or STRING

This solution will list the class or control structure name followed by the strings which match the STRING that may contain inside them. If the are not contained, the class defenition would be printed. A small tweak on awk will print all the function/ class header with the string only if they are present

print class and string only if the STRING is present

$ awk '/:$/{header=$0} /STRING/{print header; print $0}' input
class my_class(stuff):
     line of code containing STRING

What it does

  • /:$/{header=$0} if line matches the regex :$, assign the class/function header to header varialbe.

  • /STRING/{print header; print $0} if line matches STRING print the header followed by the entire record, $0

Felisha answered 10/11, 2014 at 4:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.