使用 find、wc 和 sed 计算行数
我试图使用 sed 来计算基于特定扩展名的所有行。
find -name '*.m' -exec wc -l {} \; | sed ...
我试图执行以下操作,如何将 sed 包含在这一特定行中以获得总数。
I was trying to use sed to count all the lines based on a particular extension.
find -name '*.m' -exec wc -l {} \; | sed ...
I was trying to do the following, how would I include sed in this particular line to get the totals.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您还可以使用以下命令从 wc 获得良好的格式:
You may also get the nice formatting from wc with :
这里的大多数答案不适用于大量文件。如果文件名列表对于单个命令行调用来说太长,有些会中断,而另一些则效率低下,因为
-exec
为每个文件启动一个新进程。我相信一个强大而有效的解决方案是:以这种方式使用
cat
就可以了,因为它的输出直接通过管道传输到wc
中,因此只有少量文件内容立即保存在内存中。如果单次调用cat
的文件太多,cat
将被多次调用,但所有输出仍将通过管道传输到单个wc< /代码> 过程。
Most of the answers here won't work well for a large number of files. Some will break if the list of file names is too long for a single command line call, others are inefficient because
-exec
starts a new process for every file. I believe a robust and efficient solution would be:Using
cat
in this way is fine, as its output is piped straight intowc
so only a small amount of the files' content is kept in memory at once. If there are too many files for a single invocation ofcat
,cat
will be called multiple times, but all the output will still be piped into a singlewc
process.您可以通过单个
wc
实例cat
所有文件来获取总行数:You can
cat
all files through a singlewc
instance to get the total number of lines:在现代 GNU 平台上 wc 和 find take -print0 和 -files0-from 参数,可以将它们组合成一个命令,用于计算文件中的行数,并在末尾添加总计。例子:
On modern GNU platforms wc and find take -print0 and -files0-from parameters that can be combined into a command that count lines in files with total at the end. Example:
您还可以使用 sed 来代替 wc 来计算行数:
其中
'$='
是一个“特殊变量”,用于保留行数编辑您
也可以尝试类似 sloccount
you could use sed also for counting lines in place of wc:
where
'$='
is a "special variable" that keep the count of linesEDIT
you could also try something like sloccount
嗯,如果您有很多文件,尤其是大文件,使用 cat 解决方案可能会出现问题。
正如我测试的那样,第二个解决方案不提供总数,仅提供每个文件的行数。
我更喜欢这样的东西:
无论您有多少文件和多大的文件,这都会快速完成工作。
Hm, solution with cat may be problematic if you have many files, especially big ones.
Second solution doesn't give total, just lines per file, as I tested.
I'll prefer something like this:
This will do the job fast, no matter how many and how big files you have.
sed 不是合适的计数工具。使用 awk 代替:
使用 + 代替 \;强制 find 每找到 N 个文件就调用 awk (就像使用 xargs 一样)。
sed is not the proper tool for counting. Use awk instead:
Using + instead of \; forces find to call awk every N files found (like with xargs).
对于大目录我们应该使用:
For big directories we should use: