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

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

wc -l *.php 

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

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

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


当前回答

如果您只需要PHP文件中的总行数,那么即使在安装了GnuWin32的Windows下,也可以使用非常简单的单行命令。这样地:

cat `/gnuwin32/bin/find.exe . -name *.php` | wc -l

您需要指定find.exe的确切位置,否则将执行Windows提供的find.exe(来自类似DOS的旧命令),因为它可能在环境PATH中的GnuWin32之前,并且具有不同的参数和结果。

请注意,在上面的命令中,应该使用反引号,而不是单引号。

其他回答

这里有一个使用旧Python(至少适用于Python2.6)的灵活应用程序,结合了Shizzmo可爱的一行程序。只需在类型列表中填写源文件夹中要计算的文件类型,然后让它飞起来:

#!/usr/bin/python

import subprocess

rcmd = "( find ./ -name '*.%s' -print0 | xargs -0 cat ) | wc -l"
types = ['c','cpp','h','txt']

sum = 0
for el in types:
    cmd = rcmd % (el)
    p = subprocess.Popen([cmd],stdout=subprocess.PIPE,shell=True)
    out = p.stdout.read().strip()
    print "*.%s: %s" % (el,out)
    sum += int(out)
print "sum: %d" % (sum)

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陷阱(计数进入,而不是行!!!)

在Windows PowerShell上尝试以下操作:

dir -Recurse *.php | Get-Content | Measure-Object -Line

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

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

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

或者用现代语法:

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

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