分类: LINUX
2007-01-17 09:50:24
find,grep和exec的使用
find是查找文件,而grep是在文件中查找字符串。
1.man find的部分说明:
-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 exe-
cuted in the starting directory.
find . -name "*.txt"或者find . -name *.txt
在当前目录下查找*.txt文件。结果中当前目录的路径以./表示。
[root@VIAC3-03 root]# find . -name *.txt
./pet.txt
find ~ -name "*.txt"或者find . -name *.txt
在当前目录及其子目录下查找*.txt文件。结果中当前路径会显示。示例:
[root@VIAC3-03 root]# find ~ -name *.txt
/root/pet.txt
find ~ -name *.txt -exec ls -l {} \;
在当前目录及其子目录下查找*.txt文件,并将查找
到的文件信息显示出来。注意:{}和\之间有空格;不要少了最后的分号“;”,否则提示find: missing argument to
`-exec',这个意思并不是说没有exec参数,而是exec后面的参数不对。示例:
[root@VIAC3-03 root]# find ~ -name *.txt -exec ls -l {} \;
-rw-r--r-- 1 root root 272 Oct 16 17:47 /root/pet.txt
find ~ -name "*.txt" -exec grep "Gwen" {} -nH \;
在当前目录中查找*.txt文件,并在这些查找到的文件的内容中搜索字符串"Gwen",将含有字符串"Gwen"的文件名(包括路径)和字符串所在行及行号显示出来。示例:
[root@VIAC3-03 root]# find ~ -name "*.txt" -exec grep "Gwen" {} -nH \;
/root/pet.txt:2:Claws Gwen cat m 1994-03-17 \N
/root/pet.txt:6:Chirpy Gwen bird f 1998-09-11 \N
/root/pet.txt:7:Whistler Gwen bird \N 1997-12-09 \N
2. grep的用法和常用选项
grep "Gwen" *.txt
在当前目录下所有.txt文件中查找字符串"Gwen"。示例:
[root@VIAC3-03 root]# grep "Gwen" *.txt
Claws Gwen cat m 1994-03-17 \N
Chirpy Gwen bird f 1998-09-11 \N
Whistler Gwen bird \N 1997-12-09 \N
grep -iH "gwen" *.txt
在当前目录下所有.txt文件中不区分大小写地查找字符串"gwen",结果中显示文件名和字符串所在行。示例:
[root@VIAC3-03 root]# grep -iH "gwen" *.txt
pet.txt:Claws Gwen cat m 1994-03-17 \N
pet.txt:Chirpy Gwen bird f 1998-09-11 \N
pet.txt:Whistler Gwen bird \N 1997-12-09 \N
常用选项:
-c 只输出匹配行的计数。
-i 不区分大小写(只适用于单字符)。
-h 查询多文件时不显示文件名。
-l 查询多文件时只输出包含匹配字符的文件名。
-n 显示匹配行及行号。
-s 不显示不存在或无匹配文本的错误信息。
-v 显示不包含匹配文本的所有行。