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

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

wc -l *.php 

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

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

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


当前回答

lines=0 ; for file in *.cpp *.h ; do lines=$(( $lines + $( wc -l $file | cut -d ' ' -f 1 ) )) ; done ; echo $lines

其他回答

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

 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.

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

wc -l **/*.php

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

shopt -s globstar

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

您可以使用专门为此目的而构建的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
-------------------------------------------------------------------------------

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

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

或者用现代语法:

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

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

不同之处:

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

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