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

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

wc -l *.php 

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

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

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


当前回答

我使用了从源项目目录启动的内联脚本:

 for i in $(find . -type f); do rowline=$(wc -l $i | cut -f1 -d" "); file=$(wc -l $i | cut -f2 -d" "); lines=$((lines + rowline)); echo "Lines["$lines"] " $file "has "$rowline"rows."; done && unset lines

产生此输出的:

Lines[75]  ./Db.h has 75rows.
Lines[143]  ./Db.cpp has 68rows.
Lines[170]  ./main.cpp has 27rows.
Lines[294]  ./Sqlite.cpp has 124rows.
Lines[349]  ./Sqlite.h has 55rows.
Lines[445]  ./Table.cpp has 96rows.
Lines[480]  ./DbError.cpp has 35rows.
Lines[521]  ./DbError.h has 41rows.
Lines[627]  ./QueryResult.cpp has 106rows.
Lines[717]  ./QueryResult.h has 90rows.
Lines[828]  ./Table.h has 111rows.

其他回答

$cd directory
$wc -l* | sort -nr

不同之处:

wc -l `tree -if --noreport | grep -e'\.php$'`

这很好,但您需要在当前文件夹或其子文件夹中至少有一个*.php文件,否则wc会停止。

如果您想保持简单,请去掉中间人,只需使用所有文件名调用wc:

wc -l `find . -name "*.php"`

或者用现代语法:

wc -l $(find . -name "*.php")

只要任何目录名或文件名中没有空格,这就可以工作。只要您没有数以万计的文件(现代shell支持非常长的命令行)。您的项目有74个文件,因此您有足够的空间进行扩展。

在类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
-------------------------------------------------------------------------------

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

wc -l **/*.php

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

shopt -s globstar

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