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

其他回答

到目前为止,没有一个答案能解决带空格的文件名问题。

此外,如果树中路径的总长度超过shell环境大小限制(在Linux中默认为几兆字节),则所有使用xargs的路径都会失败。

这是一个以非常直接的方式解决这些问题的方法。子shell处理带有空格的文件。awk汇总了单个文件wc输出的流,因此它不应该耗尽空间。它还将exec限制为仅文件(跳过目录):

find . -type f -name '*.php' -exec bash -c 'wc -l "$0"' {} \; | awk '{s+=$1} END {print 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

对于Windows,一个简单快捷的工具是LocMetrics。

对于另一个衬垫:

( find ./ -name '*.php' -print0 | xargs -0 cat ) | wc -l

它处理带有空格的名称,只输出一个数字。

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

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

或者用现代语法:

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

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