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



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

cd mydir
wc -l *
..
11723 total

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

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

没有用。

你可能想要这个:

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

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

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

也许您正在寻找exec find 的选项。

find . -type f -exec wc -l {} ; | awk '{total += $1} END {print total}'

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

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

如果你想在两个或更多不同类型的文件上使用它,你可以把-o选项

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

另一种选择是使用递归 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计算与任何事物('')匹配的行数,因此基本上只计算行数。

我会建议类似

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

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

使用格式计算 java 代码行数的示例:

一个衬垫

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

awk 部分:

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

示例结果

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

这里的游戏有点晚了,但这不也行吗? find . -type f | wc -l

这将计算"find"命令输出的所有行。 您可以微调"查找"以显示所需的任何内容。 我用它来计算子目录的数量,在一个特定的子目录中,在深树中:find ./*/*/*/*/*/*/TOC -type d | wc -l . 输出: 76435 . (只是在没有所有中间星号的情况下进行查找会产生错误。

最新更新