使用shell搜索匹配文件

前两天面tx都有问到这个问题,我知道大致能通过find和grep实现,但是具体没写过.刚刚无事翻了下命令手册,发现find的一个动作:

ACTIONS
    -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.  See the EXAMPLES section for examples of the use of the -exec option.  The specified command is  run  once for  each  matched  file.   The command is executed in the starting directory.   There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.

从描述来看就是执行命令,其数据来源于find的结果,如果命令返回0(即成功)则输出.

结合grep搜索:

find ./ -name "*.php" -exec grep "system" {} \;

执行,返回的是文件内容,需要返回文件名则需要对grep命令使用-l参数:

find ./ -name "*.php" -exec grep -l "system" {} \;

标签: shell, find, grep, exec

添加新评论