WC,一下子就联想到公厕了吧?如果没有,那么我们好像不是一代人啊。
Shell命令也有这么个wc,它是十分好用的统计文件的命令呢。
先看看的帮助,通常这是我们了解shell命令的第一途径。
$ wc --help
Usage: wc [OPTION]... [FILE]...
or: wc [OPTION]... --files0-from=F
Print newline, word, and byte counts for each FILE, and a total line if
more than one FILE is specified. With no FILE, or when FILE is -,
read standard input. A word is a non-zero-length sequence of characters
delimited by white space.
The options below may be used to select which counts are printed, always in
the following order: newline, word, character, byte, maximum line length.
-c, --bytes print the byte counts
-m, --chars print the character counts
-l, --lines print the newline counts
--files0-from=F read input from the files specified by
NUL-terminated names in file F;
If F is - then read names from standard input
-L, --max-line-length print the length of the longest line
-w, --words print the word counts
--help display this help and exit
--version output version information and exit
这个命令会打印给定文件的行数,字数和字节数,通常我们要和其他命令一起使用,如ls,find。
下面会通过几个小需求来演示一下它的用法。
1.统计出Android源码中frameworks下base目录的java文件个数
kitkat/frameworks$ find base/ -name *.java | wc -l
4119
2.统计base/cmds目录下所有java文件的行数
/frameworks$ find base/cmds/ -name *.java | xargs cat | grep -v ^$ | wc -l
5780
注:当我用此命令统计代码行数时发现一个有趣的问题,用上述命令统计java文件行数没有问题,统计xml文件时,发现结果的行数太少。
我直接用find . -name *.xml,找出的文件也不太对。原来要加上双引号才行。下面的统计才是对的:
find -name "*.xml" | xargs cat | grep -v ^$ | wc -l
3.找出cmds文件夹下java文件行数最多的那个,并打印出行数。
很好的题目,估计要写个脚本才行。算给自己留个作业吧。
4.统计文件夹数目
统计某文件夹下文件的个数
ls -l |grep "^-"|wc -l
统计某文件夹下目录的个数
ls -l |grep "^d"|wc -l
统计文件夹下文件的个数,包括子文件夹里的
ls -lR|grep "^-"|wc -l
如统计/home/han目录(包含子目录)下的所有js文件则:
ls -lR /home/han|grep js|wc -l 或 ls -l "/home/han"|grep "js"|wc -l
统计文件夹下目录的个数,包括子文件夹里的
ls -lR|grep "^d"|wc -l