个人工具

UbuntuHelp:Find/zh

来自Ubuntu中文

跳转至: 导航, 搜索


Find命令简介

GNU中的find命令通过名称、大小、读写时间等限制条件来在一个目录及其子目录中查找相关文件。当找到你想要的文件时,find的默认操作是显示这些文件的文件名。GNU find命令安装于每一个Ubuntu系统上。此页面是由find命令的手册页(你可以使用"man find"命令来查看手册页)来完成的。

Find基础入门

find命令的基本语法是:

find [-H] [-L] [-P] [path...] [expression]

现在我们通常忽略[-H] [-L] [-P]选项, 请查询find的手册页来明白以上选项的含义。从 [path...]开始,find查找一个目录及其子目录,在任何的表达式之前,你应当指定find命令查找的起始路径。

find . # 在当前目录查找
find /home/user1 /home/user2   #在目录home/user1和 /home/user2中查找
find # 与"find . "命令相同,如果没有指定查找的路径,那么默认使用当前目录

The above commands will print the names of all the files present in the hierarchy below the starting directories passed to find as arguments. "files" can be link, directories, hidden files ...

查找特定文件名的文件

Of course, find would just be a poor version of ls without the [expression] part, let's start by the most common and perhaps most simple example:

find dir -name 'myfile' 

The test -name 'name' will only search for an exact match of the name. This means that the above command will find, in the directory dir, a file named "myfile" but not a file named "myfile.txt" or "thisismyfile". If you are looking for a file with "myfile" in the name somewhere, you should instead use the following:

find dir -name '*myfile*' 

Here, the * is a wildcard, and can stand for any number of characters (number, letter, space...). It is a basic form of a pattern. See the find manual page for more on patterns. The most important thing here is: Do not forget to put quotes around your pattern. If the pattern is not quoted, it will be replace by the shell by the list of files matching the pattern in the current directory. For example, if your current directory contains the file mytestfile and the directory myfiles, and the myfiles directory that has the file test.txt.

$ ls
myfiles  mytestfile
$ ls myfiles/
test.txt

and we run the above find command

$ find . -name *test* #<-- wrong
./mytestfile

Not exactly what we expected. What has happened is the shell (Command Line Interface program) has interpreted *test* and matched it to mytestfile. mytestfile is what the shell passed as an argument to the find command. We need to stop the shell interpreting *test* before passing it to find. We do this by putting single quotes (') around the pattern. You might have used an unquoted pattern before and it was working, this is because if the pattern doesn't match anything in the current directory the shell leaves the pattern unchanged. Of course it's better not to rely on what might or might not be in the current directory..