我们有一个PHP应用程序,希望统计特定目录及其子目录下的所有代码行。
我们不需要忽视评论,因为我们只是想得到一个粗略的想法。
wc -l *.php
该命令对于给定的目录非常有效,但它忽略了子目录。我想下面的评论可能有用,但它返回了74,这绝对不是这样。。。
find . -name '*.php' | wc -l
重新输入目录中所有文件的正确语法是什么?
我们有一个PHP应用程序,希望统计特定目录及其子目录下的所有代码行。
我们不需要忽视评论,因为我们只是想得到一个粗略的想法。
wc -l *.php
该命令对于给定的目录非常有效,但它忽略了子目录。我想下面的评论可能有用,但它返回了74,这绝对不是这样。。。
find . -name '*.php' | wc -l
重新输入目录中所有文件的正确语法是什么?
当前回答
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陷阱(计数进入,而不是行!!!)
其他回答
使用find的-exec和awk。我们来了:
find . -type f -exec wc -l {} \; | awk '{ SUM += $0} END { print SUM }'
此代码段查找所有文件(-type f)。要按文件扩展名查找,请使用-name:
find . -name '*.py' -exec wc -l '{}' \; | awk '{ SUM += $0; } END { print SUM; }'
您没有指定有多少个文件或所需的输出。
这可能是您想要的:
find . -name '*.php' | xargs wc -l
Try:
find . -name '*.php' | xargs wc -l
或(当文件名包含特殊字符(如空格)时)
find . -name '*.php' | sed 's/.*/"&"/' | xargs wc -l
SLOCCount工具也可能有帮助。
它将提供准确的源代码行计数你指向的层次结构,以及一些额外的统计数据。
排序输出:
查找-名称“*.php”| xargs wc-l | sort-nr
您可以使用专门为此目的而构建的cloc实用程序。它报告每种语言的行数,以及其中有多少行是注释等。CLOC在Linux、Mac和Windows上都可用。
用法和输出示例:
$ cloc --exclude-lang=DTD,Lua,make,Python .
2570 text files.
2200 unique files.
8654 files ignored.
http://cloc.sourceforge.net v 1.53 T=8.0 s (202.4 files/s, 99198.6 lines/s)
-------------------------------------------------------------------------------
Language files blank comment code
-------------------------------------------------------------------------------
JavaScript 1506 77848 212000 366495
CSS 56 9671 20147 87695
HTML 51 1409 151 7480
XML 6 3088 1383 6222
-------------------------------------------------------------------------------
SUM: 1619 92016 233681 467892
-------------------------------------------------------------------------------
我是这样做的:
以下是lineCount.c文件实现:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getLinesFromFile(const char*);
int main(int argc, char* argv[]) {
int total_lines = 0;
for(int i = 1; i < argc; ++i) {
total_lines += getLinesFromFile(argv[i]); // *argv is a char*
}
printf("You have a total of %d lines in all your file(s)\n", total_lines);
return 0;
}
int getLinesFromFile(const char* file_name) {
int lines = 0;
FILE* file;
file = fopen(file_name, "r");
char c = ' ';
while((c = getc(file)) != EOF)
if(c == '\n')
++lines;
fclose(file);
return lines;
}
现在打开命令行并键入gcc-lineCount.c,然后键入/a.out*.txt文件。
这将显示目录中以.txt结尾的文件的总行数。