编写shell命令来查找php文件目录中的长if语句

问题描述 投票:0回答:1

我在 php 中有一个嵌套的文件目录,其中一些可能有 if 和 else 条件

if (condition) {
  // ~100 lines of code
}

我想快速找到那些在 if 或 else 条件内具有长主体的文件中的[文件/if 或 else 条件的开头]。花括号内有 > 100 行

例如:

File1:
    if (condition) {
      // >100 lines of code
    } else {
     // 50 lines of code
    }
    ...
    if (condition) {
      // 10 lines of code
    }
File2:
   if (condition) {
     // 2 lines
   }

应该返回 File1 中第一个 if 条件的行号,因为它的左括号和右括号内有 100 多行。 if 条件也可以嵌套

php bash shell unix awk
1个回答
0
投票

如果不为 PHP 编写解析器,您就无法稳健地完成这项工作,但如果您对一个简单、尽力而为的工具感到满意,该工具将适用于您显示的格式,其中

if
仅作为第一个“单词”出现在行,如果它是 if 条件的开始,并且匹配的
}
始终缩进,与
if
相同,那么只需使用强制 POSIX 工具,您就可以执行以下操作(未经测试,因为您没有提供示例输入和我们可以测试的预期输出):

find . -name '*.php' -exec     awk -v numLines=100 '
        match($0,/^[[:space:]]*if[[:space:](]/) {
            begNr[++depth] = FNR
            endRe[depth] = "^" substr($0,1,RLENGTH-3) "}"
        }
        depth && ( $0 ~ endRe[depth] ) {
            if ( (FNR - begNr[depth]) >= (numLines + 2) ) {
                print FILENAME, "match started at line", begNr[depth]
            }
            depth--
        }
    ' {} +
© www.soinside.com 2019 - 2024. All rights reserved.