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

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

wc -l *.php 

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

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

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


当前回答

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

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

其他回答

如果您只需要PHP文件中的总行数,那么即使在安装了GnuWin32的Windows下,也可以使用非常简单的单行命令。这样地:

cat `/gnuwin32/bin/find.exe . -name *.php` | wc -l

您需要指定find.exe的确切位置,否则将执行Windows提供的find.exe(来自类似DOS的旧命令),因为它可能在环境PATH中的GnuWin32之前,并且具有不同的参数和结果。

请注意,在上面的命令中,应该使用反引号,而不是单引号。

如果您希望结果按行数排序,只需在第一个答案中添加|sort或|sort-r(-r表示降序),如下所示:

find . -name '*.php' | xargs wc -l | sort -r

类似于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:]]*$'

您需要一个简单的for循环:

total_count=0
for file in $(find . -name *.php -print)
do
    count=$(wc -l $file)
    let total_count+=count
done
echo "$total_count"

我是这样做的:

以下是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结尾的文件的总行数。