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

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

wc -l *.php 

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

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

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


当前回答

如果您希望结果按行数排序,只需在第一个答案中添加|sort或|sort-r(-r表示降序),如下所示:

find . -name '*.php' | xargs wc -l | sort -r

其他回答

您不需要所有这些复杂且难以记忆的命令。您只需要一个名为行计数器的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

非常简单:

find /path -type f -name "*.php" | while read FILE
do
    count=$(wc -l < $FILE)
    echo "$FILE has $count lines"
done

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

 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.

一个简单的方法将很快,将使用find的所有搜索/过滤功能,当文件太多时不会失败(数字参数溢出),可以很好地处理名称中带有有趣符号的文件,而不使用xargs,并且不会启动大量无用的外部命令(感谢find的-exec)。干得好:

find . -name '*.php' -type f -exec cat -- {} + | wc -l

我的Windows系统上安装了BusyBox。这就是我所做的。

ECHO OFF
for /r %%G in (*.php) do (
busybox grep . "%%G" | busybox wc -l
)