find命令用来在指定目录下查找文件,任何位于参数之前的字符串都将被视为欲查找的目录名。如果使用该命令时,不设置任何参数,则find命令将在当前目录下查找子目录与文件,并且将查找到的子目录和文件全部进行显示。

查找的基本语法为:find dir [options] expression,在dir目录查找符合expression的文件,默认会递归查找。

一、基础用法

1.1 根据名字和类型查找

  • -name filename:直接查找该文件名的文件。
  • -type filetype:通过文件类型查找文件。

    文件类型包括:f:普通文件 b:块设备文件 c:字符设备文件 d:目录 l:链接文档 s:套接字文件

# 查找当前目录下以.tar.gz结尾的名字
ma@ubuntu:/data/software$ find . -name "*.tar.gz"
./pip-9.0.1.tar.gz
./php-5.6.33.tar.gz
./node-v9.4.0-linux-x64.tar.gz
./LuaJIT-2.0.5.tar.gz
./mysql-5.6.38-linux-glibc2.12-x86_64.tar.gz
./go1.10.1.linux-amd64.tar.gz
./gcc-centos6.tar.gz
./cmake-3.11.0-rc3.tar.gz

# 查找当前目录下的所有文件夹,不递归查询
[ma@ma software]$ find . -maxdepth 1 -type d
./gcc-7.2.0
./go1.4
./setuptools-36.5.0
./lua-5.3.4
./openssl-1.0.2l
./build
./zlib-1.2.11
./vim
./gdb-8.1

1.2 设置查找深度

通过-maxdepth选项控制查找的深度:

# 默认会递归查询,子菜单中符合条件的也会被列出来
ma@ubuntu:/data/software$ find . -name "*.zip"
./Python-2.7.14/Lib/test/zipdir.zip
./setuptools-36.6.0.zip
./php-5.6.33/ext/phar/tests/zip/files/badalias4.phar.zip
./php-5.6.33/ext/phar/tests/zip/files/frontcontroller3.phar.zip
./php-5.6.33/ext/phar/tests/zip/files/encrypted.zip
./php-5.6.33/ext/phar/tests/zip/files/frontcontroller2.phar.zip
./php-5.6.33/ext/phar/tests/zip/files/compress_unsup2.zip
./php-5.6.33/ext/phar/tests/zip/files/zlib_alias.phar.zip
./php-5.6.33/ext/zip/examples/test.zip

# 加上maxdepth之后控制查询的深度
ma@ubuntu:/data/software$ find . -maxdepth 1 -name "*.zip"
./setuptools-36.6.0.zip

1.3 时间属性控制

  • -atime +n/-n:访问或执行的时间大于或小于n天的文件。
  • -ctime +n/-n:写入,更改inode属性(如更改所有者、权限或者链接)的时间大于或小于n天的文件。
  • -mtime +n/-n:表示写入时间大于或小于n天的文件,该参数用的最多。
  • -mmin +n/-n:表示mtime在n分钟内的文件。

二、正则表达式查询

使用正则表达式查询需要的选项有两个:-regextype-regex

-regextype指定正则匹配的类型,可用的选项有很多,常见的有:‘‘awk’, ‘egrep’, ‘ed’, ‘emacs’, ‘grep’, ‘sed’等,不同匹配模式匹配的结果不一样。默认是emacs,但是默认和常用的正则不太一致,达不到想要的效果:

# 默认匹配模式打不到匹配的效果
ma@ubuntu:/data/software$ find . -maxdepth 1  -regex "(.*?gz|.*?zip)"
# 使用awk的正则匹配
ma@ubuntu:/data/software$ find . -maxdepth 1 -regextype "awk" -regex "(.*?gz|.*?zip)"
./pip-9.0.1.tar.gz
./php-5.6.33.tar.gz
./lua-5.3.4.tar.gz
./cmake-3.11.1.tar.gz
./Python-2.7.14.tgz
./gcc-7.2.0.tar.gz
./glibc-2.15.tar.gz
./libiconv-1.15.tar.gz
./autoconf-2.68.tar.gz
./nginx.tar.gz
./node-v9.4.0-linux-x64.tar.gz
./LuaJIT-2.0.5.tar.gz
./setuptools-36.6.0.zip
./mysql-5.6.38-linux-glibc2.12-x86_64.tar.gz
./go1.10.1.linux-amd64.tar.gz
./gcc-centos6.tar.gz
./cmake-3.11.0-rc3.tar.gz
最后修改:2018 年 05 月 04 日
如果觉得我的文章对你有用,请随意赞赏