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

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

wc -l *.php 

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

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

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


当前回答

Try:

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

或(当文件名包含特殊字符(如空格)时)

find . -name '*.php' | sed 's/.*/"&"/' | xargs  wc -l

SLOCCount工具也可能有帮助。

它将提供准确的源代码行计数你指向的层次结构,以及一些额外的统计数据。

排序输出:

查找-名称“*.php”| xargs wc-l | sort-nr

其他回答

POSIX公司

与这里的大多数其他答案不同,这些答案适用于任何POSIX系统、任何数量的文件以及任何文件名(除非另有说明)。


每个文件中的行数:

find . -name '*.php' -type f -exec wc -l {} \;
# faster, but includes total at end if there are multiple files
find . -name '*.php' -type f -exec wc -l {} +

每个文件中的行,按文件路径排序

find . -name '*.php' -type f | sort | xargs -L1 wc -l
# for files with spaces or newlines, use the non-standard sort -z
find . -name '*.php' -type f -print0 | sort -z | xargs -0 -L1 wc -l

每个文件中的行,按行数降序排序

find . -name '*.php' -type f -exec wc -l {} \; | sort -nr
# faster, but includes total at end if there are multiple files
find . -name '*.php' -type f -exec wc -l {} + | sort -nr

所有文件中的总行数

find . -name '*.php' -type f -exec cat {} + | wc -l

您没有指定有多少个文件或所需的输出。

这可能是您想要的:

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

一个简单的方法将很快,将使用find的所有搜索/过滤功能,当文件太多时不会失败(数字参数溢出),可以很好地处理名称中带有有趣符号的文件,而不使用xargs,并且不会启动大量无用的外部命令(感谢find的-exec)。干得好:

find . -name '*.php' -type f -exec cat -- {} + | wc -l

在类Unix系统上,有一个叫做cloc的工具,它提供代码统计信息。

我在我们的代码库中的一个随机目录中运行,它显示:

      59 text files.
      56 unique files.
       5 files ignored.

http://cloc.sourceforge.net v 1.53  T=0.5 s (108.0 files/s, 50180.0 lines/s)
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
C                               36           3060           1431          16359
C/C++ Header                    16            689            393           3032
make                             1             17              9             54
Teamcenter def                   1             10              0             36
-------------------------------------------------------------------------------
SUM:                            54           3776           1833          19481
-------------------------------------------------------------------------------

您可以使用名为codel(link)的实用程序。这是一个简单的Python模块,可以用彩色格式计算行数。

安装

pip install codel

用法

要计算C++文件的行数(扩展名为.cpp和.h),请使用:

codel count -e .cpp .h

您也可以忽略一些.gitignore格式的文件/文件夹:

codel count -e .py -i tests/**

它将忽略测试/文件夹中的所有文件。

输出如下所示:

您还可以使用-s标志缩短输出。它将隐藏每个文件的信息,只显示每个扩展名的信息。示例如下: