Find Exec 用法


find /home -size +512k 查大于512k的文件

find / -size +100000k 查大于100m的文件


find -exec 命令很好用 

-exec command ;
               Execute command; true if 0 status is returned.   All   following   arguments   to find are taken to be arguments to the command until an   argument   consisting of #;' is encountered.   The string {}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find.   Both of these constructions might need to be escaped (with a \') or quoted to   protect   them   from   expansion   by the shell.   The command is executed in the starting directory.
-exec 参数后面跟的是 command命令,注意点如下:
command命令的终止,使用 ';' (分号)来判定,在后面必须有一个 ';'
'{}',使用{}来表示文件名,也就是find前面处理过程中过滤出来的文件,用于command命令进行处理
特别强调,对于不同的系统,直接使用分号可能会有不同的意义, 使用转义符 '\'在分号前明确说明,对于前面我们遇到的问题,主要就是这个原因引起的!
举例:
1.查询所有保护字符串“Hello”的文件
find / -exec grep "Hello" {} \;
2.删除所有临时文件
find / -name "*.tmp" -exec rm -f {} \;
在svn 上执行:
find . -type f -name "*.sh" -exec svn propset svn:executable on {} \;

=========

grep find 命令组合使用 

find grep 组合的一个例子
用来查找所有".h"文件中的含有“helloworld”字符串的文件.
find  -name "*.h" -exec grep "helloworld" {} \;


使用exec或ok来执行shell命令

使用find时,只要把想要的操作写在一个文件里,就可以用exec来配合find查找,很方便的

在有些操作系统中只允许-exec选项执行诸如l s或ls -l这样的命令。大多数用户使用这一选项是为了查找旧文件并删除它们。建议在真正执行rm命令删除文件之前,最好先用ls命令看一下,确认它们是所要删除的文件。

exec选项后面跟随着所要执行的命令或脚本,然后是一对儿{ },一个空格和一个\,最后是一个分号。为了使用exec选项,必须要同时使用print选项。如果验证一下find命令,会发现该命令只输出从当前路径起的相对路径及文件名。

例如:为了用ls -l命令列出所匹配到的文件,可以把ls -l命令放在find命令的-exec选项中

# find . -type f -exec ls -l { } \;
-rw-r--r-- 1 root root 34928 2003-02-25 ./conf/httpd.conf
-rw-r--r-- 1 root root 12959 2003-02-25 ./conf/magic
-rw-r--r-- 1 root root 180 2003-02-25 ./conf.d/README

上面的例子中,find命令匹配到了当前目录下的所有普通文件,并在-exec选项中使用ls -l命令将它们列出。
在/logs目录中查找更改时间在5日以前的文件并删除它们:

$ find logs -type f -mtime +5 -exec rm { } \;

记住:在shell中用任何方式删除文件之前,应当先查看相应的文件,一定要小心!当使用诸如mv或rm命令时,可以使用-exec选项的安全模式。它将在对每个匹配到的文件进行操作之前提示你。

在下面的例子中, find命令在当前目录中查找所有文件名以.LOG结尾、更改时间在5日以上的文件,并删除它们,只不过在删除之前先给出提示。

$ find . -name "*.conf" -mtime +5 -ok rm { } \;
< rm ... ./conf/httpd.conf > ? n

按y键删除文件,按n键不删除。

任何形式的命令都可以在-exec选项中使用。

在下面的例子中我们使用grep命令。find命令首先匹配所有文件名为“ passwd*”的文件,例如passwd、passwd.old、passwd.bak,然后执行grep命令看看在这些文件中是否存在一个sam用户。

# find /etc -name "passwd*" -exec grep "sam" { } \;
sam:x:501:501::/usr/sam:/bin/bash

find . -print|xargs grep "abcd" *
find . -print|xargs grep "abcd" *.java

标签:linux find grep
分类:Linux


猜你喜欢

转载自dbaspider.iteye.com/blog/2201900