我们有一个PHP应用程序,希望统计特定目录及其子目录下的所有代码行。

我们不需要忽视评论,因为我们只是想得到一个粗略的想法。

wc -l *.php 

该命令对于给定的目录非常有效,但它忽略了子目录。我想下面的评论可能有用,但它返回了74,这绝对不是这样。。。

find . -name '*.php' | wc -l

重新输入目录中所有文件的正确语法是什么?


当前回答

如果文件太多,最好只查找总行数。

find . -name '*.php' | xargs wc -l | grep -i ' total' | awk '{print $1}'

其他回答

类似于Shizzmo的回答,但更丑陋、更准确。如果您经常使用它,请将其修改为适合并放入脚本中。

此示例:

正确排除不是代码的路径(find根本不遍历)过滤出复合扩展名和您希望忽略的其他文件仅包含指定类型的实际文件忽略空行给出一个总数

find . \! \( \( -path ./lib -o -path ./node_modules -o -path ./vendor -o -path ./any/other/path/to/skip -o -wholename ./not/this/specific/file.php -o -name '*.min.js' -o -name '*.min.css' \) -prune \) -type f \( -name '*.php' -o -name '*.inc' -o -name '*.js' -o -name '*.scss' -o -name '*.css' \) -print0 | xargs -0 cat | grep -vcE '^[[:space:]]*$'

首先更改要知道行数的目录。

例如,如果我想知道一个名为sample的目录的所有文件中的行数,请给出$cd示例。

然后尝试命令$wc-l*。这将返回每个文件的行数以及结尾处整个目录中的行总数。

仅适用于来源:

wc `find`

要过滤,只需使用grep:

wc `find | grep .php$`

我是这样做的:

以下是lineCount.c文件实现:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int getLinesFromFile(const char*);

int main(int argc, char* argv[]) {
   int total_lines = 0;
   for(int i = 1; i < argc; ++i) {
       total_lines += getLinesFromFile(argv[i]); // *argv is a char*
   }

   printf("You have a total of %d lines in all your file(s)\n",    total_lines);
   return 0;
}


int getLinesFromFile(const char* file_name) {
    int lines = 0;
    FILE* file;
    file = fopen(file_name, "r");
    char c = ' ';
    while((c = getc(file)) != EOF)
        if(c == '\n')
            ++lines;
    fclose(file);
    return lines;
}

现在打开命令行并键入gcc-lineCount.c,然后键入/a.out*.txt文件。

这将显示目录中以.txt结尾的文件的总行数。

cat \`find . -name "*.php"\` | wc -l