3

I would like to match files that contain try (in one line) and consecutive catch (in another line) at least N lines later (to find very long try-catches and try to get rid of them). I mean, the first catch after try should be be N lines later.

Is there a good way to do this with standard UNIX tools like grep, sed, awk?

I experimented with doing twice grep -A <number> -B <number> but it's good at the reverse thing, i.e. finding the try-catches that are not longer than N lines.

1 Answer 1

5

What about this solution?

awk -v gap=5 '
       /try/ {inside=1; a=0; next}
       inside{a++}
      /catch/ && inside && (a>=gap) {print "line",NR, "gap of",a,$0; inside=0}
' file

Explanation

  • -v gap=5 gives the gap size. If there are some try/catch whose lines are in a distance bigger than this, they will be printed.
  • /try/ {inside=1; a=0; next} if the line contains a try, then the counter begins. inside is the flag that means we are checking a try/catch. a is the counter of lines.
  • inside{a++} if we are inside, ++ the counter while reading a line.
  • /catch/ && inside && (a>gap) if the line contains a "catch" and we are inside the "try" condition and the counter is bigger than what we set with gap, then do {print "line",NR, "gap of",a,$0; inside=0}.

Test

$ cat a
hello
try
line1
catch

blabla
try
line1
line2
line3
line4
catch
end

With a gap of 5:

$ awk -v gap=5 '/try/ {inside=1; a=0; next} inside{a++} /catch/ && inside && (a>=gap) {print "line",NR, "gap of",a,$0; inside=0}' a
line 12 gap of 5 catch

With a gap of 2:

$ awk -v gap=2 '/try/ {inside=1; a=0; next} inside{a++} /catch/ && inside && (a>=gap) {print "line",NR, "gap of",a,$0; inside=0}' a
line 4 gap of 2 catch
line 12 gap of 5 catch

You must log in to answer this question.

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