chaihongjun.me

linux下统计文件或者目录数量的方法

  首先我们知道linux下面有这样的一个命令:

wc -l

根据帮助信息:

[root@www wangluobu]# 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

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
For complete documentation, run: info coreutils 'wc invocation'

我们可以了解到这个wc,其实是word count的意思,用来计数的,可以记录字节,记录字符,按照行数记录以及记录单词的数量等。可以用来统计每一个文件以上的数据。但是这个命令无法单独使用,一般是和ls命令结合在一起:

ls | wc -l

上面的命令是统计当前有几个文件(包含文件和目录,不含子目录),ls 横向列出文件名,然后通过管道用wc格式化输出需要的结果。


有时候当前目录既有文件"-",又有目录"d",想只统计其一呢?

ls | grep "^-" | wc -l #只统计当前目录下一般文件的数量(不含目录)
ls | grep "^d" | wc -l #只统计当前目录下目录的数量(不含一般文件,不含子目录)


如果想统计当前目录下的文件数量,包括子目录:

ls -R|grep "^-"|wc -l

如果想统计当前目录下的文件夹数量,包括子目录:

ls -R|grep "^d"|wc -l

只要是递归只需要添加R参数即可。

grep "^-" 
grep "^d"

分别指的是过滤一般文件或目录



知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。作者:柴宏俊»