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

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

wc -l *.php 

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

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

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


当前回答

首先更改要知道行数的目录。

例如,如果我想知道一个名为sample的目录的所有文件中的行数,请给出$cd示例。

然后尝试命令$wc-l*。这将返回每个文件的行数以及结尾处整个目录中的行总数。

其他回答

您不需要所有这些复杂且难以记忆的命令。您只需要一个名为行计数器的Python工具。

快速概述

这就是你获得工具的方法

$ pip install line-counter

使用line命令获取当前目录下的文件计数和行计数(递归):

$ line
Search in /Users/Morgan/Documents/Example/
file count: 4
line count: 839

如果你想要更多的细节,只需使用行-d。

$ line -d
Search in /Users/Morgan/Documents/Example/
Dir A/file C.c                                             72
Dir A/file D.py                                           268
file A.py                                                 467
file B.c                                                   32
file count: 4
line count: 839

这个工具最好的部分是,你可以在其中添加一个.gitignore类配置文件。你可以设置规则来选择或忽略要计数的文件类型,就像你在.gitignore'中所做的那样。

更多描述和用法如下:https://github.com/MorganZhang100/line-counter

cat \`find . -name "*.php"\` | wc -l

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

如果文件太多,最好只查找总行数。

find . -name '*.php' | xargs wc -l | grep -i ' total' | awk '{print $1}'

还有一种变化:)

$ find . -name '*.php' | xargs cat | wc -l

这将给出总金额,而不是逐个文件。

添加在找到后使其工作。