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

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

wc -l *.php 

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

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

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


当前回答

非常简单:

find /path -type f -name "*.php" | while read FILE
do
    count=$(wc -l < $FILE)
    echo "$FILE has $count lines"
done

其他回答

您不需要所有这些复杂且难以记忆的命令。您只需要一个名为行计数器的Python工具。

快速概述

这就是你获得工具的方法

$ pip install line-counter

使用line命令获取当前目录下的文件计数和行计数(递归):

$ line
Search in /Users/Morgan/Documents/Example/
file count: 4
line count: 839

如果你想要更多的细节,只需使用行-d。

$ line -d
Search in /Users/Morgan/Documents/Example/
Dir A/file C.c                                             72
Dir A/file D.py                                           268
file A.py                                                 467
file B.c                                                   32
file count: 4
line count: 839

这个工具最好的部分是,你可以在其中添加一个.gitignore类配置文件。你可以设置规则来选择或忽略要计数的文件类型,就像你在.gitignore'中所做的那样。

更多描述和用法如下:https://github.com/MorganZhang100/line-counter

我还可以添加另一个OS X条目,这个条目使用普通的旧find with exec(我更喜欢使用xargs,因为我在过去看到过使用xarg的非常大的查找结果集的奇怪结果)。

因为这是针对OS X的,所以我还将过滤添加到.h或.m文件中—确保将所有文件复制到最后!

find ./ -type f -name "*.[mh]" -exec wc -l {}  \; | sed -e 's/[ ]*//g' | cut -d"." -f1 | paste -sd+ - | bc

我是这样做的:

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

WC-L?最好使用GREP-C^

wc-l?错误的

wc命令计算新行代码,而不是行!当文件中的最后一行没有以新的行代码结尾时,这将不会被计算在内!

如果仍然需要计数行,请使用grep-c^。完整示例:

# This example prints line count for all found files
total=0
find /path -type f -name "*.php" | while read FILE; do
     # You see, use 'grep' instead of 'wc'! for properly counting
     count=$(grep -c ^ < "$FILE")
     echo "$FILE has $count lines"
     let total=total+count #in bash, you can convert this for another shell
done
echo TOTAL LINES COUNTED:  $total

最后,注意wc-l陷阱(计数进入,而不是行!!!)

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

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