Linux中find常见用法

原文地址:http://tutorials.hostucan.cn/article-linux-find



find命令主要是用于文件查找, 非常有用, 但对于初学者, 会发现它有点怪异. 为啥呢? 因为用的少, 用多了, 习惯了, 也就不怪异了. 让我们先从一个简单例子开始.
$ find / -name test
./backup/ modules/field/modules/test
$
“查找根目录下名称为’test’的文件”, 这条命令会让系统查找所有文件, 包括挂载的文件设备. 这可能需要花费一段时间, 尤其是查找网络共享硬盘. 不过, 我们可以通过参数-mount告诉, 系统忽略挂载设备:
$ find / -mount -name test
find命令格式如下:
find [path] [options] [tests] [actions]
[path]

路径; 应该不难理解. 这里可以使用绝对路径, 也快成使用相对路径.
[options]

参数; 比较常用的参数用:
-depth: 先查找子目录再查看当前目录 -follow: 跟踪查找连接文件 -maxdepths N: 子目录递归最大深度 -mount(or -xdev): 忽略挂载文件
[tests]

条件匹配;
-atime -N/N/+N: 最后一次访问文件的时间在 N天内/N天/N天前 -mtime -N/N/+N: 最后一次修改文件的时间在 N天内/N天/N天前 -name pattern: 与pattern相匹配的文件(包括目录) -newer f1 !f2: 比文件f1新的文件, 比文件f2旧的文件 -type b/d/c/p/l/f: 文件类型为: 块设备/目录/字符设备/管道/链接/文件 -user username: 文件的所有者是username
我们可以通过以下操作符, 将匹配条件 连起来:
-not (!): 方向匹配 -and (-a): 而且 -or (-o): 或者
我们还可以通过括号将一些匹配符号合并. 例如
\(-newer -o -name ‘*test’ \)
现在举一个稍微有点复杂的例子, 查找当天被访问过或修改过的文件, 文件名包含’python’, 而起文件所有者是’anthony’:
# find / \( -atime -1 -or -mtime -1 \) -and -name '*python*' -and -user 'anthony'
/home/anthony/svn_code/subversion-1.7.2/subversion/bindings/swig/python
/home/anthony/svn_code/subversion-1.7.2/subversion/bindings/ctypes-python
/home/anthony/python
/home/anthony/python/Python-3.2.2/build/temp.linux-x86_64-3.2/home/anthony/python
/home/anthony/python/Python-3.2.2/Tools/unicode/python-mappings
/home/anthony/.local/lib/python3.2
#
[actions]

操作;
-exec command: 执行命令, 具体介绍见后文. -ok command: 和-exec一样, 除了命令执行需要用户许可. -print: 打印文件名 -ls: 列出文件详细信息
现在举例说明-exec command
anthony@z:~$ find -mtime -1 -type f -exec ls -l {} \;
-rw-r--r-- 1 anthony anthony 0 Apr 5 12:04 ./search/search.txt
-rw------- 1 anthony anthony 22997 Apr 5 12:04 ./.viminfo
-rw------- 1 anthony anthony 125 Apr 5 14:25 ./.lesshst
anthony@z:~$
简单地说, -exec或-ok, 将查询到的文件作为参数传递给后面的命令执行, 而参数的位置用{}标识, 即命令中, “{}”替换成find查找出来的文件名, 最后”\;”表示结束符.

猜你喜欢

转载自wangxiaoxu.iteye.com/blog/2147453
今日推荐