find 的用法:
find [path] [options] [tests] [actions]
path可以为绝对路径,比如/, /usr/include 等等,也可以为相对路径,比如当前路径 .
option 有下面几个:
-depth: search the contents of a directory before looking at the directory itself
-follow: follow symbolic links
-maxdepths N: search at most N leves of the directory when searching
-mount (or -xdev): don't search directories on other file systems.
test 常用的有下面几个:
-atime N: the file was last accessed N days ago
-mtime N: the file was last modified N days ago
-name pattern: the name of the file, excluding any path, matches the pattern provided. The pattern must always be in quotes .
-newer otherfile: the file is newer than the file otherfile.
-type C: the file is of type C, where C can be a particular type; the most common are "d" for a directory and "f" for a regular file.For other types consult the manuel pages.
-user username: the file is owned by the user with the given name.
test可以用操作符结合起来,!=-not (invert the test), -a = -and (both tests must be true), -o = -or (either test must be true)
action 常用的有下面几个:
-exec command: execute a command. This action must be terminated with a /; character pair;
-ok command: like -exec, except that it prompts for user confirmation of each file on which it will carry out the command before executing the command. This action must be terminated with a /; character pair;
-print: print out the name of the file
-ls: use the command ls -dils on the current file
举例如下:
查找当前目录下所有.c文件并显示:find . -name "*.c" -print
输出:
./password.c
./screenmenu.c
./test_LF_CR.c
./menu1.c
./test_getchar.c
grep 的用法:
grep [options] PATTERN [FILES]
if not filenames are given, it searches standard input.
options常用的有:
-c: rather than print matching lines, print a count of the numbers of lines that match
-E: turn on extended expressions
-h: suppress the normal prefixing of each output line with the name of the file it was found in.
-i: ignore case
-l: list the names of the files with match lines; don't output the actual matched line
-v: invert the matching pattern to select nonmatching lines, rather than matching lines.
举例如下:
查找password.c 中的include:grep include password.c
输出:
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
查找password.c 中的include的个数:grep -c include password.c
输出:
3
find和grep结合起来使用:
查找所有.c文件中的include: find . -name "*.c" -exec grep include {} /;
输出:
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <termios.h>
#include <term.h>
#include <curses.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
这里使用 {} 给-exec 或者 -ok 中的命令传递参数,执行时被替换为当前文件的绝对路径。