我们有一个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

其他回答

至少在OS X上,其他一些答案中列出的find+xarg+wc命令在大型列表中多次打印“总计”,但没有给出完整的总计。我能够使用以下命令获得.c文件的单个总数:

查找-名称'*.c'-print0|xargs-0wc-l|grep-v total|awk'{sum+=$1;}END{print“sum:”sum;}'

如果您使用窗口,请执行以下两个步骤:

安装cloc,例如为admin打开cmd并编写下一个代码=>choco安装cloc然后在项目文件夹中使用cd或openterminal并编写下一个代码=>cloc项目示例

步骤如下:

p.s.需要使用生成项目和node_modules移动或删除文件夹

有一个叫做sloccount的小工具来计算目录中的代码行。

应该注意的是,它做的比你想要的更多,因为它忽略空行/注释,按编程语言分组结果,并计算一些统计数据。

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

wc -l **/*.php

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

shopt -s globstar

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

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