在Mac中统计代码行数,find的命令怎么用

2016-12-14

先来看怎么用

1
2
3
4
5
# 统计文件类型是`*.m`,`*.mm`,`*.cpp`,`*.h`,`*.rss`的文件代码行数
find . "(" -name "*.m" -or -name "*.mm" -or -name "*.cpp" -or -name "*.h" -or -name "*.rss" ")" | xargs wc -l

# 统计js文件行数
find . "(" -name "*.js" ")" | xargs wc -l

仔细看一下

这条命令主要包含两部分,

  • find
  • wc

find是过滤出想要统计的文件,wc是统计,他们中间通过|管道连接

xargs:由于很多命令不支持|管道来传递参数

xargs 可以读入 stdin 的资料,并且以空白字元或断行字元作为分辨,将 stdin 的资料分隔成为 arguments 。

find .: 列出当前目录及子目录下所有文件和文件夹

来自: http://man.linuxde.net/find

wc

http://man.linuxde.net/wc

  • -c或–bytes或——chars:只显示Bytes数;
  • -l或——lines:只显示列数;
  • -w或——words:只显示字数。

如果不带参数

1
2
3
➜  public  >wc index.html
117 627 14703 index.html
行数 Bytes数 字数

来自: http://man.linuxde.net/wc

find

http://man.linuxde.net/find

忽略某个子目录

1
find . "./node_modules" -prune
  • -o: 等同-or, 或的意思,类似的条件判断还有与-a,非!

忽略大小写

1
2
3
4
5
6
7
find /home -iname "HelloWorld.txt"

可以匹配上
helloworld.txt
HELLOWORLD.txt
Helloworld.TXT
...

匹配文件路径或文件

1
2
3
4
5
# 文件夹或文件名包含local
find /usr/ -path "*local*"

# 文件夹包含local
find /usr/ -path "*/local/*"
  • -path: 指定字符串作为寻找目录的关键字

正则匹配

1
find . -regex ".*\(\.txt\|\.pdf\)$"

根据文件大小来搜索

1
2
3
4
# 搜索大于1G的文件
find . -type f -size +1G

find . -type f -size -1k
  • b —— 块(512字节)
  • c —— 字节
  • w —— 字(2字节)
  • k —— 千字节
  • M —— 兆字节
  • G —— 吉字节

####

根据文件性质来分类

1
2
# 显示所有目录
find . -type d
  • f 普通文件
  • l 符号连接
  • d 目录
  • c 字符设备
  • b 块设备
  • s 套接字
  • p Fifo

基于目录深度搜索

1
2
3
4
5
# 向下深度限制为3
find . -maxdepth 3 -type f

# 向下深度超过2的文件
find . -mindepth 2 -type f

要列出所有长度为零的文件

来自: http://man.linuxde.net/find

1
find . -empty