我们有一个PHP应用程序,希望统计特定目录及其子目录下的所有代码行。
我们不需要忽视评论,因为我们只是想得到一个粗略的想法。
wc -l *.php
该命令对于给定的目录非常有效,但它忽略了子目录。我想下面的评论可能有用,但它返回了74,这绝对不是这样。。。
find . -name '*.php' | wc -l
重新输入目录中所有文件的正确语法是什么?
我们有一个PHP应用程序,希望统计特定目录及其子目录下的所有代码行。
我们不需要忽视评论,因为我们只是想得到一个粗略的想法。
wc -l *.php
该命令对于给定的目录非常有效,但它忽略了子目录。我想下面的评论可能有用,但它返回了74,这绝对不是这样。。。
find . -name '*.php' | wc -l
重新输入目录中所有文件的正确语法是什么?
当前回答
您需要一个简单的for循环:
total_count=0
for file in $(find . -name *.php -print)
do
count=$(wc -l $file)
let total_count+=count
done
echo "$total_count"
其他回答
如果你使用的是Linux(我认为你是),我推荐我的工具polyglot。它比sloccount或cloc都快得多,而且比sloccount更具特色。
您可以使用
poly .
or
poly
因此,它比一些复杂的Bash脚本更加用户友好。
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
这里有一个使用旧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)
如果使用相当新的Bash(或ZSH)版本,则要简单得多:
wc -l **/*.php
在Bash shell中,这需要设置globstar选项,否则**glob运算符不是递归的。要启用此设置,请发出
shopt -s globstar
要使其永久化,请将其添加到一个初始化文件(~/.bashrc、~/.bah_profile等)中。
如果您希望结果按行数排序,只需在第一个答案中添加|sort或|sort-r(-r表示降序),如下所示:
find . -name '*.php' | xargs wc -l | sort -r