我们有一个PHP应用程序,希望统计特定目录及其子目录下的所有代码行。
我们不需要忽视评论,因为我们只是想得到一个粗略的想法。
wc -l *.php
该命令对于给定的目录非常有效,但它忽略了子目录。我想下面的评论可能有用,但它返回了74,这绝对不是这样。。。
find . -name '*.php' | wc -l
重新输入目录中所有文件的正确语法是什么?
我们有一个PHP应用程序,希望统计特定目录及其子目录下的所有代码行。
我们不需要忽视评论,因为我们只是想得到一个粗略的想法。
wc -l *.php
该命令对于给定的目录非常有效,但它忽略了子目录。我想下面的评论可能有用,但它返回了74,这绝对不是这样。。。
find . -name '*.php' | wc -l
重新输入目录中所有文件的正确语法是什么?
当前回答
类似于Shizzmo的回答,但更丑陋、更准确。如果您经常使用它,请将其修改为适合并放入脚本中。
此示例:
正确排除不是代码的路径(find根本不遍历)过滤出复合扩展名和您希望忽略的其他文件仅包含指定类型的实际文件忽略空行给出一个总数
find . \! \( \( -path ./lib -o -path ./node_modules -o -path ./vendor -o -path ./any/other/path/to/skip -o -wholename ./not/this/specific/file.php -o -name '*.min.js' -o -name '*.min.css' \) -prune \) -type f \( -name '*.php' -o -name '*.inc' -o -name '*.js' -o -name '*.scss' -o -name '*.css' \) -print0 | xargs -0 cat | grep -vcE '^[[:space:]]*$'
其他回答
如果您希望结果按行数排序,只需在第一个答案中添加|sort或|sort-r(-r表示降序),如下所示:
find . -name '*.php' | xargs wc -l | sort -r
您需要一个简单的for循环:
total_count=0
for file in $(find . -name *.php -print)
do
count=$(wc -l $file)
let total_count+=count
done
echo "$total_count"
我知道这个问题被标记为bash,但您试图解决的问题似乎也与PHP有关。
塞巴斯蒂安·伯格曼(Sebastian Bergmann)编写了一个名为PHPLOC的工具,它可以满足您的需求,并为您提供项目复杂性的概述。这是其报告的一个例子:
Size
Lines of Code (LOC) 29047
Comment Lines of Code (CLOC) 14022 (48.27%)
Non-Comment Lines of Code (NCLOC) 15025 (51.73%)
Logical Lines of Code (LLOC) 3484 (11.99%)
Classes 3314 (95.12%)
Average Class Length 29
Average Method Length 4
Functions 153 (4.39%)
Average Function Length 1
Not in classes or functions 17 (0.49%)
Complexity
Cyclomatic Complexity / LLOC 0.51
Cyclomatic Complexity / Number of Methods 3.37
正如您所看到的,从开发人员的角度来看,所提供的信息非常有用,因为它可以在您开始使用项目之前大致告诉您项目有多复杂。
WC-L?最好使用GREP-C^
wc-l?错误的
wc命令计算新行代码,而不是行!当文件中的最后一行没有以新的行代码结尾时,这将不会被计算在内!
如果仍然需要计数行,请使用grep-c^。完整示例:
# This example prints line count for all found files
total=0
find /path -type f -name "*.php" | while read FILE; do
# You see, use 'grep' instead of 'wc'! for properly counting
count=$(grep -c ^ < "$FILE")
echo "$FILE has $count lines"
let total=total+count #in bash, you can convert this for another shell
done
echo TOTAL LINES COUNTED: $total
最后,注意wc-l陷阱(计数进入,而不是行!!!)
仅适用于来源:
wc `find`
要过滤,只需使用grep:
wc `find | grep .php$`