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

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

wc -l *.php 

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

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

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


当前回答

您可以使用专门为此目的而构建的cloc实用程序。它报告每种语言的行数,以及其中有多少行是注释等。CLOC在Linux、Mac和Windows上都可用。

用法和输出示例:

$ cloc --exclude-lang=DTD,Lua,make,Python .
    2570 text files.
    2200 unique files.
    8654 files ignored.

http://cloc.sourceforge.net v 1.53  T=8.0 s (202.4 files/s, 99198.6 lines/s)
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
JavaScript                    1506          77848         212000         366495
CSS                             56           9671          20147          87695
HTML                            51           1409            151           7480
XML                              6           3088           1383           6222
-------------------------------------------------------------------------------
SUM:                          1619          92016         233681         467892
-------------------------------------------------------------------------------

其他回答

另一个获取所有文件总和的命令(当然是Linux)

find ./ -type f -exec wc -l {}  \; | cut -d' ' -f1 | paste -sd+ | bc

与其他答案的主要区别:

使用find-exec,使用膏(带切口),使用bc

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

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

安装

pip install codel

用法

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

codel count -e .cpp .h

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

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

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

输出如下所示:

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

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

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

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