如何计算code线包括子目录 [英] How to count lines of code including sub-directories

查看:127
本文介绍了如何计算code线包括子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想指望code的线路中的一个项目。如果所有的文件都在同一目录下我可以执行:

Suppose I want to count the lines of code in a project. If all of the files are in the same directory I can execute:

cat * | wc -l

然而,如果有子目录,这是行不通的。对于这项工作的猫就必须有一个递归模式。我怀疑这可能是一个xargs的工作,但我不知道是否有一个更优雅的解决方案?

However, if there are sub-directories, this doesn't work. For this to work cat would have to have a recursive mode. I suspect this might be a job for xargs, but I wonder if there is a more elegant solution?

推荐答案

首先,你不需要使用来计算行。这就是所谓的猫(UUOC)没用使用反模式。要计算行的文件在当前目录下,使用 厕所

First you do not need to use cat to count lines. This is an antipattern called Useless Use of Cat (UUoC). To count lines in files in the current directory, use wc:

wc -l * 

然后找到命令递归的子目录:

find . -name "*.c" -exec wc -l {} \;


  • 是顶级目录,开始从搜索名称

    • . is the name of the top directory to start searching from

      -name* .c在是你感兴趣的。

      -exec 给出要执行的命令

      {} 是find命令的结果传递给命令(此处 WC-L

      {} is the result of the find command to be passed to the command (here wc-l)

      \\ 表示命令的结尾

      此命令生成与他们的行数找到的所有文件的列表,如果你想为全部的文件中找到,您可以使用find列出文件(用<$总和C $ C> -print 选项),比使用xargs的通过这个列表作为参数,以WC-L。

      This command produces a list of all files found with their line count, if you want to have the sum for all the files found, you can use find to list the files (with the -print option) and than use xargs to pass this list as argument to wc-l.

      find . -name "*.c" -print | xargs wc -l 
      

      编辑解决罗伯特宝洁评论(感谢):(!)如果你在文件名中的空格或换行符,那么你必须使用 -print0 选项,而不是 -print xargs的-null 这样的文件名列表与空结尾的字符串交换。

      EDIT to address Robert Gamble comment (thanks): if you have spaces or newlines (!) in file names, then you have to use -print0 option instead of -print and xargs -null so that the list of file names are exchanged with null-terminated strings.

      find . -name "*.c" -print0 | xargs -0 wc -l
      

      Unix的理念是有只做一件事,把它做好的工具。

      The Unix philosophy is to have tools that do one thing only, and do it well.

      这篇关于如何计算code线包括子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆