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

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

wc -l *.php 

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

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

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


当前回答

不包括空行:

find . -name "*.php" | xargs grep -v -c '^$' | awk 'BEGIN {FS=":"} { $cnt = $cnt + $2} END {print $cnt}'

包括空行:

find . -name "*.php" | xargs wc -l

其他回答

有一个叫做sloccount的小工具来计算目录中的代码行。

应该注意的是,它做的比你想要的更多,因为它忽略空行/注释,按编程语言分组结果,并计算一些统计数据。

如果使用相当新的Bash(或ZSH)版本,则要简单得多:

wc -l **/*.php

在Bash shell中,这需要设置globstar选项,否则**glob运算符不是递归的。要启用此设置,请发出

shopt -s globstar

要使其永久化,请将其添加到一个初始化文件(~/.bashrc、~/.bah_profile等)中。

我的Windows系统上安装了BusyBox。这就是我所做的。

ECHO OFF
for /r %%G in (*.php) do (
busybox grep . "%%G" | busybox wc -l
)

对于我来说,更常见和简单的是,假设您需要计算不同扩展名的文件(例如,也是本地文件):

wc $(find . -type f | egrep "\.(h|c|cpp|php|cc)" )

我是这样做的:

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