1

I am trying to grep for various python coding anti patterns, so that they can be caught during our builds. I am having a hard time utilizing grep to do the match over new line.

Anti pattern to search for:

except:
  pass

The below patten works great in Intellij, but does not work when applied with grep.

except:\s+pass

Please recommend on how to achieve this.

4
  • This is old, but may still be relevant: stackoverflow.com/questions/2686147/… Commented Feb 12, 2020 at 19:18
  • just use pylint
    – iruvar
    Commented Feb 12, 2020 at 23:50
  • Using regular expressions to parse structured data like source code is the MOTHER of anti-patterns.
    – user313992
    Commented Feb 13, 2020 at 23:38
  • By the term grep you mean Shell (Bash, Sh, Ash, etc.)? If so, edit the TAGs in your query because there is also a Shell and at least modify the term "grep" to "grep command in the Shell (command-line)". If you mean system Shell, then there are many solutions (awk, sed, grep, printf, using python interpreter, etc.).
    – s3n0
    Commented Mar 4, 2020 at 14:35

1 Answer 1

1

One solution with pcregrep which stands for Perl Compatible Regular Expressions GREP.

pcregrep -M "^except:\n\s+pass$" file

where -M, --multiline allows patterns to match more than one line.

The regular expression matches the literal :except: at the beginning of a line followed by a line break, 0 or more white spaces (matching the most amount possible) and by the literal pass at the end of the line.

1
  • @iruvar See my updated answer. Commented Feb 13, 2020 at 10:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .