在所有子目录上使用wc来计算行的总和

时间:2012-12-05 16:33:36

标签: linux bash text-files console-application

如何使用wc计算所有子目录中所有文件的所有行?

cd mydir
wc -l *
..
11723 total

man wc建议wc -l --files0-from=-,但我不知道如何生成所有文件的列表NUL-terminated names

find . -print | wc -l --files0-from=-

没用。

7 个答案:

答案 0 :(得分:78)

你可能想要这个:

find . -type f -print0 | wc -l --files0-from=-

如果您只想要总行数,可以使用

find . -type f -exec cat {} + | wc -l

答案 1 :(得分:7)

也许您正在寻找exec的{​​{1}}选项。

find

答案 2 :(得分:4)

要计算您可以使用的特定文件扩展名的所有行,

find . -name '*.fileextension' | xargs wc -l

如果你想要两种或更多种不同类型的文件,你可以把-o选项

find . -name '*.fileextension1' -o -name '*.fileextension2' | xargs wc -l

答案 3 :(得分:4)

另一种选择是使用递归grep:

grep -hRc '' . | awk '{k+=$1}END{print k}'

awk只是添加数字。使用的grep选项是:

   -c, --count
          Suppress normal output; instead print a count of matching  lines
          for  each  input  file.  With the -v, --invert-match option (see
          below), count non-matching lines.  (-c is specified by POSIX.)
   -h, --no-filename
          Suppress the prefixing of file names on  output.   This  is  the
          default  when there is only one file (or only standard input) to
          search.
   -R, --dereference-recursive
          Read all files under each directory,  recursively.   Follow  all
          symbolic links, unlike -r.
因此,grep计算匹配任何内容的行数(''),因此基本上只计算行数。

答案 4 :(得分:1)

基于ДМИТРИЙМАЛИКОВ的回答:

使用格式对Java代码行进行计数的示例:

一个班轮

find . -name *.java -exec wc -l {} \; | awk '{printf ("%3d: %6d %s\n",NR,$1,$2); total += $1} END {printf ("     %6d\n",total)}'

awk部分:

{ 
  printf ("%3d: %6d %s\n",NR,$1,$2); 
  total += $1
} 
END {
  printf ("     %6d\n",total)
}

示例结果

  1:    120 ./opencv/NativeLibrary.java
  2:     65 ./opencv/OsCheck.java
  3:      5 ./opencv/package-info.java
        190

答案 5 :(得分:0)

我会建议像

这样的东西
find ./ -type f | xargs wc -l | cut -c 1-8 | awk '{total += $1} END {print total}'

答案 6 :(得分:-1)

这里比赛迟到了,但这不也有效吗? find . -type f | wc -l

这会计算' find'输出的所有行。命令。你可以微调发现'展示你想要的任何东西。我用它来计算深树中一个特定子目录中子目录的数量:find ./*/*/*/*/*/*/TOC -type d | wc -l。输出:76435。 (只是在没有所有介入星号的情况下进行查找会产生错误。)

相关问题