linux命令五find

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/uotail/article/details/88105836

1、NAME命令名称

  find - search for files in a directory hierarchy 在目录层次结构中搜索文件

2、SYNOPSIS大纲

find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression]

其实[-H] [-L] [-P] [-D debugopts] [-Olevel]这几个选项并不常用(至少在我的日常工作中,没有用到过),上面的find命令的常用形式可以简化为:
       find [starting-point...] [expression]
       [starting-point...] find命令所查找的目录路径。例如用.来表示当前目录,用/来表示系统根目录。

 find *.txt       默认查找当前目录下的txt文件
 find  . *.txt    会查询当前目录下./目录下的文件  会有重复

在这里插入图片描述
.

3、DESCRIPTION说明

 This manual page documents the GNU version of find.  GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see sec‐ tion OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name.  If no starting-point is specified, `.' is assumed.
    查找系统上的文件。在给定路径指定的每个目录树中,它根据优先级规则(参见下面的“操作符”)从左到右计算给定表达式,直到结果已知。当表达式的左侧被确定为for和运算为假,或for或运算为真时,结果是“已知的”。此时,查找移动到下一个路径,直到搜索完所有路径。

find是在linux系统上处理文件的基本工具,功能非常强大。它可以单独使用来定位文件,也可以与其他程序一起对这些文件执行操作。

find命令是一个无处不在命令,是linux中最有用的命令之一。find命令用于:在一个目录(及子目录)中搜索文件,你可以指定一些匹配条件,如按文件名、文件类型、用户甚至是时间戳查找文件

实时查找工具,通过遍历指定路径完成文件查找
特点:查找速度略慢 (因为是实时查找,需要经历每个路径才能完成查找)
   精确查找
   可能只搜索用户具备读取和执行权限的目录 (没有权限无法进行操作)

4、EXPRESSION表达式

The part of the command line after the list of starting points is the expression.  This is a kind of query specification describing how we match files and what we do with the files that were matched.  An expression is  composed of a sequence of things:
 在起始点列表之后的命令行部分是表达式。这是一种查询规范,描述如何匹配文件以及如何处理匹配的文件。表达式由以下部分组成一连串的事情:

4.1、Tests

 Tests return a true or false value, usually on the basis of some property of a file we are considering.  The -empty test for example is true only when the current file is empty.
测试返回true或false值,通常基于我们正在考虑的文件的某些属性。例如-empty测试仅在当前文件为空时才为真。

4.2、Actions

Actions  have  side  effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful.  The -print action for example prints the name of the current file on the standard output.
操作有副作用(例如在标准输出上打印一些东西),并返回true或false,这通常取决于它们是否成功。例如,-print操作将打印标准输出上的当前文件。

4.3、Global options

 Global options affect the operation of tests and actions specified on any part of the command line.  Global options always return true.  The -depth option for example makes find traverse the file system in a  depth-first  order.
  全局选项影响命令行任何部分上指定的测试和操作的操作。全局选项总是返回true。例如-depth选项使find以深度优先的方式遍历文件系统秩序。

4.5、Positional options

Positional  optiona  affect only tests or actions which follow them.  Positional options always return true.  The -regextype option for example is positional, specifying the regular expression dialect for regulat expres‐sions occurring later on the command line.
  位置选项只影响随后的测试或操作。位置选项总是返回true。例如,-regextype选项是定位的,指定regulat expres‐的正则表达式方言稍后在命令行中出现的版本。

4.6、Operators

  Operators join together the other items within the expression.  They include for example -o (meaning logical OR) and -a (meaning logical AND).  Where an operator is missing, -a is assumed.
     运算符将表达式中的其他项连接在一起。它们包括-o(表示逻辑或)和-a(表示逻辑和)。如果缺少一个运算符,则假定为- 1。
If the whole expression contains no actions other than -prune or -print, -print is performed on all files for which the whole expression is true.
     如果整个表达式只包含-prune或-print操作,则对所有表达式为真的文件执行-print操作。
 The -delete action also acts like an option (since it implies -depth).
     delete操作的作用类似于一个选项(因为它意味着-depth)。

5、POSITIONAL OPTIONS 位置选项

这块不常用

       Positional options always return true.  They affect only tests occurring later on the command line.
       位置选项总是返回true。它们只影响稍后在命令行上发生的测试。

       -daystart
              Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago.  This option only affects tests which appear later on the command line.
              从今天开始测量时间(-amin, -atime, -cmin, -ctime, -mmin, -mtime),而不是从24小时之前。此选项只影响稍后出现在命令行中的测试。
       -follow
              Deprecated; use the -L option instead.  Dereference symbolic links.  Implies -noleaf.  The -follow option affects only those tests which appear after it on the command line.  Unless the -H or -L option  has  been  speci‐
              fied, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links.  The same consideration applies to -new‐
              erXY, -anewer and -cnewer.  Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself.  Using -follow causes the -lname  and  -ilname  predi‐
              cates always to return false.
              弃用;使用-L选项代替。废弃的符号链接。意味着-noleaf。follow选项只影响命令行中出现在它后面的那些测试。除非-H或-L选项已经明确
              如果指定,-follow选项的位置将更改-new谓词的行为;如果是符号链接,那么作为- updates参数列出的任何文件都将被解除引用。同样的考虑也适用于-new‐
              erXY, -anewer和- c更新。类似地,-type谓词总是匹配符号链接指向的文件类型,而不是链接本身。使用-follow会导致-lname和-ilname predi -
              cates总是返回false。

       -regextype type
              Changes  the  regular expression syntax understood by -regex and -iregex tests which occur later on the command line.  To see which regular expression types are known, use -regextype help.  The Texinfo documentation (see
              SEE ALSO) explains the meaning of and differences between the various types of regular expression.

       -warn, -nowarn
              Turn warning messages on or off.  These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories.  The default behaviour corresponds to -warn if standard
              input  is a tty, and to -nowarn otherwise.  If a warning message relating to command-line usage is produced, the exit status of find is not affected.  If the POSIXLY_CORRECT environment variable is set, and -warn is also
              used, it is not specified which, if any, warnings will be active.

6、GLOBAL OPTIONS全局选项

Global options always return true.  Global options take effect even for tests which occur earlier on the command line.  To prevent confusion, global options should specified on the command-line after the list of  start  points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing.
 全局选项总是返回true。全局选项甚至对发生在命令行前面的测试也有效。为了避免混淆,应该在命令行起点列表之后指定全局选项就在第一次测试之前,位置选项或动作。如果您在其他地方指定了全局选项,find将发出一条警告消息,解释这可能会造成混淆。

The global options occur after the list of start points, and so are not the same kind of option as -L, for example.
全局选项出现在起始点列表之后,因此与-L选项不同。

6.1、指定要搜索的目录层级

 -maxdepth levels
              Descend at most levels (a non-negative integer) levels of directories below the starting-points.  -maxdepth 0
               means only apply the tests and actions to the starting-points themselves.
               在起始点以下目录的大多数级别(非负整数)下降。maxdepth 0表示只对起点本身应用测试和操作。
 -mindepth levels
              Do not apply any tests or actions at levels less than levels (a non-negative integer).  -mindepth 1 means process all files except the starting-points.
              不要在低于级别(非负整数)的级别上应用任何测试或操作。-mindepth 1表示处理除起始点以外的所有文件。

find默认会遍历所有子目录。可以采用-maxdepth和-mindepth参数。
只列出当前目录下的普通文件。即使有子目录也不会被打印和遍历。

ubuntu@ip-172-31-3-107:~$ find . -maxdepth 1 -type f -print

在这里插入图片描述
注意:如果-type放在–maxdepth前面,find会先找出符合-type的所有文件,然后在所有匹配的文件中在找出符合指定深度的那些 但是,如果先指定目录深度,在-type,那么find先找出符合指定深度的文件后,在按-type查找,这才是最有效的搜索顺序。

6.2、不常用

  -d     A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD.
           深度的同义词,与FreeBSD、NetBSD、MacOS X和OpenBSD兼容。
 -depth Process each directory's contents before the directory itself.  The -delete action also implies -depth.
           -深度处理目录本身之前的每个目录的内容。delete操作还意味着-depth。
  -help, --help
           Print a summary of the command-line usage of find and exit.
 -ignore_readdir_race
          Normally, find will emit an error message when it fails to stat a file.  If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the
          file, no error message will be issued.    This also applies to files or directories whose names are given on the command line.  This option takes effect at the time the command line is read, which means that  you  cannot
          search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it)
          
 -mount Don't descend directories on other filesystems.  An alternate name for -xdev, for compatibility with some other versions of find.

 -noignore_readdir_race
         Turns off the effect of -ignore_readdir_race.
 -noleaf
        Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count.  This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD- ROM or MS-DOS filesystems or AFS volume mount points.  Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.'  entry.  Additionally, its subdirectories (if any) each have a `..'  entry linked  to  that  directory.   When  find  is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories(`leaf' files in the directory tree).  If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed.
 -version, --version
         Print the find version number and exit.
         -xdev  Don't descend directories on other filesystems.

7、TESTS

 Numeric arguments can be specified as  数值参数可以指定为

       +n     for greater than n, 大于n

       -n     for less than n,    小于

       n      for exactly n.      等于

7.1、根据文件时间搜索

7.1.1、指定时间访问过的文件

  -amin n
              File was last accessed n minutes ago.
              上次访问文件是在n分钟前。(access 访问、存取) 
              
              5分钟之内访问过的文件(当前目录)
              ubuntu@ip-172-31-3-107:~$ find . -amin -5

  -atime n
              File was last accessed n*24 hours ago.  
              When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago.
              上次访问文件是在24小时前。
              当find计算出该文件最后一次被访问的24小时前的时间段时,将忽略任何小数部分,因此要匹配-atime +1,两条前必须至少访问过两个文件
              
              24小时(1天)内(文件系统根目录 / 下)
              find / -atime -1

7.1.2、指定时间文件状态被改变过的文件

 -cmin n
              File's status was last changed n minutes ago.
              文件的状态上次更改是在n分钟前。
              
              当前目录及其子目录下5分钟之内 文件或目录状态改变的
              ubuntu@ip-172-31-3-107:~$ find . -cmin -5
 -ctime n
              File's status was last changed n*24 hours ago.  See the comments for -atime to understand how rounding affects the interpretation of file status change times.

              在根目录/及其子目录下一天内(24小时内)文件状态被改变的文件列表:
              ubuntu@ip-172-31-3-107:~$ find / -ctime -1

7.1.3、指定时间内被修改过的文件


 -mmin n
              File's data was last modified n minutes ago.
              文件的数据上次修改是在n分钟前。

在这里插入图片描述

  -mtime n
              File's data was last modified n*24 hours ago. 
              文件数据上次修改是在n*24小时前。 
              See the comments for -atime to understand how rounding affects the interpretation of file modification times.
              参见注释-atime了解舍入如何影响文件修改时间的解释。

7.14、不常用

  -newer file
              File was modified more recently than file.  If file is a symbolic link and the -H option or the -L option is in effect, the modification time of the file it points to is always used.

              显示在指定文件之后做出修改的文件。下面的find命令将显示所有的在ordinary_file之后创建修改的文件。
              find -newer ordinary_file
              find -newer "hello.txt"

  -newerXY reference
              Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference.   The letters X and Y can be any of the following letters:

              a   The access time of the file reference
              B   The birth time of the file reference
              c   The inode status change time of reference
              m   The modification time of the file reference
              t   reference is interpreted directly as a time

              Some  combinations are invalid; for example, it is invalid for X to be t.  Some combinations are not implemented on all systems; for example B is not supported on all systems.  If an invalid or unsupported combination of
              XY is specified, a fatal error results.  Time specifications are interpreted as for the argument to the -d option of GNU date.  If you try to use the birth time of a reference file, and the birth time  cannot  be  deter‐
              mined, a fatal error message results.  If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown.
 -used n
              File was last accessed n days after its status was last changed.
              文件上次访问是在其状态上次更改后的n天。

              列出文件或目录被改动过之后,在2日内被存取过的文件或目录
              ubuntu@ip-172-31-3-107:~/word1$ find /home -used -2   

7.2、查找空文件或目录

 -empty       File is empty and is either a regular file or a directory.
              文件是空的,它可以是常规文件,也可以是目录。

              查找空文件或目录
              ubuntu@ip-172-31-3-107:~$ find . -empty

   -executable
          Matches files which are executable and directories which are searchable (in a file name resolution sense).  This takes into account access control lists and other permissions artefacts which the -perm test ignores.  This
          test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of  the  UID
          mapping information held on the server.  Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed.

   -false Always false.

   -fstype type
          File is on a filesystem of type type.  The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs,
          tmp, mfs, S51K, S52K.  You can use -printf with the %F directive to see the types of your filesystems.

7.3、根据用户或用户组查询

 -gid n File's numeric group ID is n.
            文件的数字组ID为n。
 -uid n File's numeric user ID is n.
  -group gname
              File belongs to group gname (numeric group ID allowed).
              文件属于组gname(允许数字组ID)。
  -user uname
              File is owned by user uname (numeric user ID allowed).
              文件由用户uname拥有(允许使用数字用户ID)。
   -nogroup
              No group corresponds to file's numeric group ID.
              find -nogroup        查找没有属组的文件

  -nouser
              No user corresponds to file's numeric user ID.
              find -nouser       查找没有属主的文件

linux 查看用户的uid,gid

  1. 可以通过查看/etc/passwd文件来确定自己的uid和gid
    cat /etc/passwd | grep 你的用户名
    cat /etc/passwd | grep ubuntu
    在这里插入图片描述
    其中x后面的两个数就是uid和gid了,这里uid是1000,gid也是1000
  2. 可以直接通过id命令
    (1)查看当前用户的id
    (2)查看其它用户的id(查看root用户的所有id)

7.4、按文件硬链接数查询

 -links n
              File has n links.
              链接数为n的文件
              这里的这个链接数指的是硬链接,查看链接数应该用stat这个命令,之前有提过,所指示的位置就是显示的文件的硬链接数

在这里插入图片描述

7.5、按文件名称查询

-name pattern
              Base  of file name (the path with the leading directories removed 删除主目录的路径) matches shell pattern pattern. 
              文件的名称与shell模式匹配。
              Because the leading directories are removed, the file names considered for a match with -name will never include a slash,so `-name a/b' will never match anything (you probably need to use -path instead).  
              因为前面的目录被删除,所以与-name匹配的文件名将永远不会包含斜杠,因此“-name a/b”将永远不会匹配任何内容(您可能需要使用-path来代替)。
              A warning is issued if you try to do this, unless the environment variable POSIXLY_CORRECT is set.  
              如果您尝试这样做,则会发出警告,除非设置了环境变量POSIXLY_CORRECT。
              The metacharacters  (`*',  `?',  and `[]') match a `.' at the start of the base name (this is a change in findutils-4.2.2; see section STANDARDS CONFORMANCE below).  
              To ignore a directory and the files under it, use -prune; see an example in the description of -path.  
              若要忽略目录及其下的文件,请使用-prune;请参见-path描述中的示例。
              Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. 
              尽管包括Bash在内的一些shell在shell模式中具有特殊含义,但大括号并不被认为是特殊的。 
              The filename matching is  performed  with  the  use  of  the fnmatch(3) library function.  
              文件名匹配是使用fnmatch(3)库函数执行的。 
              Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell.
              不要忘记将模式括在引号中,以防止shell对其进行扩展。

注意: 路径必须在表达式之前(paths must percede expression)
例如当前目录含有a.c、b.c、c.c
$find . -name .c -print
find: paths must percede expression
出现这种错误的原因,shell先将
.c扩展成a.c b.c c.c
相当于命令变成:
$find . –name a.c b.c c.c -print
这是种错误使用方式。取而代之,可以对*.c加上双引号:
$find . –name “.c” -print
或者使用\,将\放在
前,避开该通配符。
$find . –name *.c -print

实例

 find . -name "*.txt"
 find . -name  "[A-Z]*"   -print   #查以大写字母开头的文件
 find /etc -name "host*"  -print #查以host开头的文件

在这里插入图片描述

不常用

 -ilname pattern
              Like -lname, but the match is case insensitive.  If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken.
              类似-lname,但匹配不区分大小写。

-iname pattern
              Like -name, but the match is case insensitive.  For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc.   The pattern `*foo*` will also match a file called '.foobar'.
              类似-name,但匹配不区分大小写。例如,模式“fo*”和“F??”匹配文件名' Foo', ' Foo', ' Foo', ' Foo'等等。模式“*foo*”也将匹配一个名为“.foobar”的文件。

 -lname pattern
              File is a symbolic link whose contents match shell pattern pattern.  The metacharacters do not treat `/' or `.' specially.  If the -L option or the -follow option is in effect, this test returns false unless the symbolic
              link is broken.
              文件是一个符号链接,其内容与shell模式模式匹配。元字符不处理' /'或'。的特别。如果-L选项或-follow选项有效,则此测试返回false,除非符号链接是坏了。

7.6、按路径path查询

  -path pattern
              File name matches shell pattern pattern.
              文件名匹配shell模式模式。
              The metacharacters do not treat `/' or `.' specially; so, for example,
              元字符不处理'/'或'.' 特别;举个例子,
                        find . -path "./sr*sc"
              will  print an entry for a directory called `./src/misc' (if one exists).  
              将打印一个目录的条目 ./src/misc (如果有的话)。
              To ignore a whole directory tree, use -prune rather than checking every file in the tree.  
              若要忽略整个目录树,请使用-prune而不是检查树中的每个文件。
              For example, to skip the directory `src/emacs' and all files and directories under it, and print the names of the other files found, do something like this:
              例如,要跳过“src/emacs”目录及其下的所有文件和目录,并打印找到的其他文件的名称,可以这样做:
                        find . -path ./src/emacs -prune -o -print
              Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line.
              请注意,模式匹配测试适用于整个文件名,从命令行中指定的一个起始点开始。
              It would only make sense to use an absolute path name here if the relevant start point is
              also an absolute path.  This means that this command will never match anything:
                        find bar -path /foo/bar/myfile -print
              Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining.  Since the concatenation will never end with a slash, -path arguments ending in a slash will match
              nothing (except perhaps a start point specified on the command line).  The predicate -path is also supported by HP-UX find and will be in a forthcoming version of the POSIX standard.

在这里插入图片描述

 -ipath pattern
              Like -path.  but the match is case insensitive.

实例

  1. 在当前目录下查找所有txt后缀文件
    find ./ -name ‘*.txt’
  2. 在当前目录下的word1目录及子目录下查找txt后缀文件
    ubuntu@ip-172-31-3-107:~$ find . -path ‘./word1*’ -name '.txt’
    -path './word1
    ’的意思是打印出路径匹配为 ‘./word1*’ 的文件
  3. 在除当前目录下的word1目录及子目录外查找txt后缀文件
    ubuntu@ip-172-31-3-107:~$ find ./ -path ‘./word1*’ -a -prune -o -name ‘*.txt’

不常用

 -wholename pattern
              See -path.  This alternative is less portable than -path.
              See -path.。这个替代方案的可移植性不如-path。

7.7、按正则表达式查询 (类似path)

选项-regex的参数和-path类似,只不过-regex是基于正则表达式来匹配文件路径的。类似的-iregex用于忽略大小写

   -regex pattern
              File  name  matches  regular expression pattern. 
              文件名与正则表达式模式匹配。
              This is a match on the whole path, not a search. 
              这是整个路径上的匹配,而不是搜索。
              For example, to match a file named `./fubar3', you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'.
              例如,匹配一个名为'的文件 `./fubar3',你可以使用正则表达式`.*bar.' 或`.*b.*3', ,而不是 `f.*r3'
              The regular expressions understood by find are by default Emacs Regular Expressions, but this can be changed with the -regextype option.
              find默认理解的正则表达式是Emacs正则表达式,但是可以使用-regextype选项进行更改。

               以PATTERN匹配整个文件路径字符串,而不仅仅是文件名称

               选项-regex的参数和-path类似,只不过-regex是基于正则表达式来匹配文件路径的。类似的-iregex用于忽略大小写
    -iregex pattern
              Like -regex, but the match is case insensitive.

实例

基于正则表达式匹配文件路径

find . -regex ".*\(\.txt\|\.pdf\)$"
 同上,但忽略大小写
 find . -iregex ".*\(\.txt\|\.pdf\)$"

7.8、按文件权限查询

 -perm mode
              File's permission bits are exactly mode (octal or symbolic). 
              文件的权限位完全是模式(八进制或符号)。
              Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string.  
              由于需要精确匹配,如果您想将此表单用于符号模式,可能必须指定一个相当复杂的模式字符串。
              For  example  `-perm g=w'  will  only  match files which have mode 0020 (that is, ones for which group write permission is the only permission set). 
              例如,' -perm g=w'只匹配模式为0020的文件(也就是说,只有组写权限集的文件)。 
              It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w',which matches any file with group write permission.  
              您更可能希望使用' /'或' -'表单,例如' -perm -g=w',它匹配具有组写权限的任何文件。
              See the EXAMPLES section for some illustrative examples.
 -perm -mode
              All of the permission bits mode are set for the file. 
              为文件设置了所有权限位模式。 
              Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. 
              符号模式以这种形式被接受,这通常是您希望使用它们的方式。
              You must specify `u', `g' or `o' if you  use  a  symbolic mode.   
              如果使用符号模式,必须指定“u”、“g”或“o”。
              See the EXAMPLES section for some illustrative examples.

 -perm /mode
              Any of the permission bits mode are set for the file.
              设置文件的任何权限位模式。  
              Symbolic modes are accepted in this form.
              这种形式接受符号模式。
              You must specify `u', `g' or `o' if you use a symbolic mode.
              如果使用符号模式,必须指定“u”、“g”或“o”。  
              See the EXAMPLES section for some illustrative examples.  
              If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000).
              如果没有设置模式中的权限位,则该测试将匹配任何文件(这里的想法是与-perm -000的行为一致)。

-perm +mode
              This is no longer supported (and has been deprecated since 2005).  Use -perm /mode instead.
              这不再受支持(并且自2005年以来一直被弃用)。使用-perm /mode代替。

7.9、按文件inode号查询

 -samefile name
              File refers to the same inode as name.   When -L is in effect, this can include symbolic links.
              文件引用与名称相同的inode。当-L生效时,这可以包括符号链接。

相同inode号的文件

查看文件的inode号用到的命令是 ls -i ,stat也能查到,圈圈出来的就是

查找当前目录下与指导文件相同inode号的文件

 ubuntu@ip-172-31-3-107:~$ find . -samefile hello.txt 

在这里插入图片描述
在这里插入图片描述

7.10、按文件大小查询

 -size n[cwbkMG]
              File uses n units of space, rounding up.  The following suffixes can be used:
              文件使用n个单位的空间,四舍五入。可以使用以下后缀:

              `b'    for 512-byte blocks (this is the default if no suffix is used)

              `c'    for bytes

              `w'    for two-byte words

              `k'    for Kilobytes (units of 1024 bytes)

              `M'    for Megabytes (units of 1048576 bytes)

              `G'    for Gigabytes (units of 1073741824 bytes)

              The size does not count indirect blocks, but it does count blocks in sparse files that are not actually allocated.  Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files  differently.   The
              `b' suffix always denotes 512-byte blocks and never 1 Kilobyte blocks, which is different to the behaviour of -ls.
              大小不计算间接块,但它计算稀疏文件中没有实际分配的块。
              请记住,printf的“%k”和“%b”格式说明符以不同的方式处理稀疏文件。“b”后缀总是表示512字节的块,而不是1千字节的块,这与-ls的行为不同。

              The  +  and  -  prefixes  signify greater than and less than, as usual.  Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c.  The former only matches empty
              files, the latter matches files from 1 to 1,048,575 bytes.
              和往常一样,+和-前缀表示大于和小于。记住,大小是四舍五入到下一个单位。因此-size -1M不等于-size -1048576c。前者只匹配空文件,后者匹配1到1,048,575字节的文件。

在当前目录下查找大于10M的文件

ubuntu@ip-172-31-3-107:~$ find . -size +100M 

在这里插入图片描述

7.11、按文件类型查询

 -type c
              File is of type c:
              查找某一类型的文件

              b      block (buffered) special 块设备文件

              c      character (unbuffered) special 字符设备文件

              d      directory 目录

              p      named pipe (FIFO) 管道文件

              f      regular file 普通文件。

              l      symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. 
                     If you want to search for symbolic links when -L is in effect, use -xtype.
                     符号链接文件。

              s      socket

              D      door (Solaris)

              b - 。 
              

分别查找当前目录下的文件和目录

              ubuntu@ip-172-31-3-107:~/word1$ find . -type f
              ubuntu@ip-172-31-3-107:~/word1$ find . -type d
              ubuntu@ip-172-31-3-107:~/word1$ find . ! -type d

              find . -type f -name ".*"  查找所有的隐藏文件
              find . -type d -name ".*"  查找所有的隐藏目录

在这里插入图片描述

不常用

-xtype c
              The  same  as  -type  unless  the file is a symbolic link.  For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'.  In
              other words, for symbolic links, -xtype checks the type of the file that -type does not check.

7.12、其他

-readable
              Matches files which are readable.  This takes into account access control lists and other permissions artefacts which the -perm test ignores.  This test makes use of the access(2) system call, and so can be fooled by NFS
              servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server.
              
 -true  Always true.
 
 -writable
              Matches files which are writable.  This takes into account access control lists and other permissions artefacts which the -perm test ignores.  This test makes use of the access(2) system call, and so can be fooled by NFS
              servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server.
              
  -context pattern
              (SELinux only) Security context of the file matches glob pattern.

8、ACTIONS 对查找出来的文件进行处理

8.1、执行删除

 -delete删除匹配文件
              Delete files; true if removal succeeded.  If the removal failed, an error message is issued.  If -delete fails, find's exit status will be nonzero (when it eventually exits).  Use of -delete automatically  turns  on  the
              `-depth' option.
              删除文件;如果移除成功,则为真。如果删除失败,则发出错误消息。如果-delete失败,find的退出状态将是非零的(当它最终退出时)。使用-delete自动打开“-depth”选项。

              Warnings: Don't forget that the find command line is evaluated as an expression, so putting -delete first will make find try to delete everything below the starting points you specified.  When testing a find command line
              that you later intend to use with -delete, you should explicitly specify -depth in order to avoid later surprises.  Because -delete implies -depth, you cannot usefully use -prune and -delete together.
              警告:不要忘记find命令行是作为表达式计算的,所以put -delete first将使find尝试删除指定起始点以下的所有内容。
              在测试以后打算与-delete一起使用的find命令行时,应该显式地指定-depth,以避免以后出现意外。因为-delete意味着-depth,所以不能同时使用-prune和-delete。

实例

 删除当前目录下所有.txt文件
 ubuntu@ip-172-31-3-107:~/word1$find . -name "*.txt" -delete
 find . -type f -name "*.txt" -delete

8.2、执行命令行

       -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  start‐
              ing directory.   There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.
              执行命令;如果返回0状态,则为true。
              下面要查找的所有参数都被视为命令的参数,直到遇到由';'组成的参数。
              字符串“{}”在命令的参数中出现的任何地方都被当前文件名所替代,而不仅仅是在find的某些版本中单独出现的参数中。
              这两种结构可能都需要转义(使用' \')或引用,以保护它们不受shell的扩展。
              有关-exec选项的使用示例,请参见示例部分。
              指定的命令对每个匹配的文件运行一次。命令在起始目录中执行。
              执行委员会的行动不可避免地存在安全问题;您应该使用-execdir选项。
              
       -exec command {} +
              This  variant  of  the  -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be
              much less than the number of matched files.  The command line is built in much the same way that xargs builds its command lines.  Only one instance of `{}' is allowed within the command.  The command is executed  in  the
              starting directory.  If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all.  This variant of -exec always returns true.
              exec操作的这个变体在选定的文件上运行指定的命令,但是命令行是通过在末尾追加每个选定的文件名来构建的;该命令的调用总数将远远少于匹配文件的数量。
              命令行构建的方式与xargs构建其命令行非常相似。在命令中只允许一个“{}”实例。命令在起始目录中执行。
              如果find遇到错误,有时会导致立即退出,因此可能根本不会运行某些挂起的命令。
              这个-exec的变量总是返回true。
       -execdir command ;

       -execdir command {} +
              Like  -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find.  This a much more secure method for invoking commands, as it
              avoids race conditions during resolution of the paths to the matched files.  As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of
              command  will  only  list  files that exist in the same subdirectory.  If you use this option, you must ensure that your $PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they
              like by leaving an appropriately-named file in a directory in which you will run -execdir.  The same applies to having entries in $PATH which are empty or which are not absolute directory names.  If  find  encounters  an
              error,  this  can  sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns
              true, while -execdir command {} ; returns true only if command returns 0.

实例

注意命令之间的空格
 ubuntu@ip-172-31-3-107:~$ find . *.txt -exec ls {} \;  
 ubuntu@ip-172-31-3-107:~$ find . *.txt -exec rm {} \;

              
 find ./ -size 0 -exec rm {} \; 删除文件大小为零的文件 (还可以以这样做:rm -i `find ./ -size 0` ) 
 find /logs -type f -mtime +5 -exec rm {  } \;   在/logs目录中查找更改时间在5日以前的文件并删除它们:
 find /var/log -type f -mtime +7 -ok rm {} \;    查找/var/log目录中更改时间在7日以前的普通文件,并在删除之前询问它们
 find / -type f -size 0 -exec ls -l {} \;        为了查找系统中所有文件长度为0的普通文件,并列出它们的完整路径:

 find . -maxdepth 1 -type f -not -name '*.*' |xargs rm  Linux反选删除文件
 find -iname "MyCProgram.c" -exec md5sum {} \;find命令来计算所有不区分大小写的文件名为“MyCProgram.c”的文件的MD5验证和。{}将会被当前文件名取代。
 find . -type f -exec ls -s {} \; | sort -n -r | head -5  列出当前目录及子目录下的5个最大的文件
 find . -type f -exec ls -s {} \; | sort -n  | head -5    查找5个最小的文件
上面的命令中,很可能你看到的只是空文件(0字节文件)。如此,你可以使用下面的命令列出最小的文件,而不是0字节文件。
 find . -not -empty -type f -exec ls -s {} \; | sort -n  | head -5

8.3、执行命令行时进行询问

 -ok command ;
              Like -exec but ask the user first.  If the user agrees, run the command.  Otherwise just return false.  If the command is run, its standard input is redirected from /dev/null.

              The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response.  This regular expression is obtained from the system if the  `POSIXLY_CORRECT'  envi‐
              ronment variable is set, or otherwise from find's message translations.  If the system has no suitable definition, find's own definition will be used.   In either case, the interpretation of the regular expression itself
              will be affected by the environment variables 'LC_CTYPE' (character classes) and 'LC_COLLATE' (character ranges and equivalence classes).
             
              -ok: 和-exec的作用相同,只不过以一种更为安全的模式来执行该参数所给出的shell命令,在执行每一个命令之前,都会给出提示,让用户来确定是否执行。

 -okdir command ;
              Like -execdir but ask the user first in the same way as for -ok.  If the user does not agree, just return false.  If the command is run, its standard input is redirected from /dev/null.

实例

ubuntu@ip-172-31-3-107:~/word1$ find . *.txt -ok ls {} \;

8.4、将查找出来得写入文件

       -fprint file
              True; print the full file name into file file.  If file does not exist when find is run, it is created; if it does exist, it is truncated.  The file names `/dev/stdout' and `/dev/stderr' are handled specially; they refer
              to the standard output and standard error output, respectively.  The output file is always created, even if the predicate is never matched.  See the UNUSUAL FILENAMES section for information about how unusual  characters
              in filenames are handled.
              真正的;将完整的文件名打印到文件文件中。
              如果find运行时文件不存在,则创建该文件;如果它确实存在,就会被截断。
              特别处理“/dev/stdout”及“/dev/stderr”等档案名称;它们分别引用标准输出和标准错误输出。
              始终创建输出文件,即使谓词从未匹配。
              有关如何处理文件名中不寻常字符的信息,请参见“不寻常文件名”一节。

实例

 ubuntu@ip-172-31-3-107:~/word1$ find . *.txt -fprint "f.txt"

在这里插入图片描述

其他

  -fprint0 file
              True;  like -print0 but write to file like -fprint.  The output file is always created, even if the predicate is never matched.  See the UNUSUAL FILENAMES section for information about how unusual characters in filenames
              are handled.

 -fprintf file format
              True; like -printf but write to file like -fprint.  The output file is always created, even if the predicate is never matched.  See the UNUSUAL FILENAMES section for information about how unusual characters in  filenames
              are handled.

  -fls file
              True; like -ls but write to file like -fprint.  The output file is always created, even if the predicate is never matched.  See the UNUSUAL FILENAMES section for information about how unusual characters in filenames  are
              handled.

8.5、对查出来得文件执行ls

   -ls    True;  list  current  file in ls -dils format on standard output.  The block counts are of 1K blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used.  See the UNUSUAL FILE‐
              NAMES section for information about how unusual characters in filenames are handled.
              真正的;在标准输出上以ls -dils格式列出当前文件。块计数为1K块,除非设置了环境变量POSIXLY_CORRECT,在这种情况下使用512字节的块。有关如何处理文件名中不寻常字符的信息,请参阅“不寻常文件名”一节。
              类似于对查找到的文件执行“ls -l”命令

实例

 ubuntu@ip-172-31-3-107:~/word1$ find . *.txt -ls

在这里插入图片描述

8.6、打印

 -print True; print the full file name on the standard output, followed by a newline.   If you are piping the output of find into another program and there is the faintest possibility that the files which you are  searching  for
              might contain a newline, then you should seriously consider using the -print0 option instead of -print.  See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled.
              在标准输出上打印完整的文件名,然后换行。
              如果您正在将find的输出管道传输到另一个程序中,并且您正在搜索的文件可能包含换行符的可能性极小,那么您应该认真考虑使用-print0选项而不是-print。
              有关如何处理文件名中不寻常字符的信息,请参见“不寻常文件名”一节。
-print0
              True;  print  the full file name on the standard output, followed by a null character (instead of the newline character that -print uses).  This allows file names that contain newlines or other types of white space to be
              correctly interpreted by programs that process the find output.  This option corresponds to the -0 option of xargs.

-printf format
              True; print format on the standard output, interpreting `\' escapes and `%' directives.  Field widths and precisions can be specified as with the `printf' C function.  Please note that many of the fields are  printed  as
              %s  rather  than  %d, and this may mean that flags don't work as you might expect.  This also means that the `-' flag does work (it forces fields to be left-aligned).  Unlike -print, -printf does not add a newline at the
              end of the string.  The escapes and directives are:

8.7立即退出

 -quit  Exit immediately.  
              立即退出。
              No child processes will be left running, but no more paths specified on the command line will be processed.
              不会留下子进程继续运行,但是不会处理命令行上指定的更多路径。  
              For example, find /tmp/foo /tmp/bar -print -quit will  print  only  /tmp/foo.   
              Any  command lines which have been built up with -execdir ... {} + will be invoked before find exits.   
              The exit status may or may not be zero, depending on whether an error has already occurred.
              退出状态可以是零,也可以不是零,这取决于是否已经发生了错误。

8.8、其他

    -prune True; if the file is a directory, do not descend into it. 
              如果文件是一个目录,不要下降到它 
              If -depth is given, false; no effect.  
              如果-depth是给定的,则为false;没有效果。
              Because -delete implies -depth, you cannot usefully use -prune and -delete together.
              因为-delete意味着-depth,所以不能同时使用-prune和-delete。

9、OPERATORS操作符

 Listed in order of decreasing precedence:
       按优先级递减排列:
       ( expr )
              Force precedence.  Since parentheses are special to the shell, you will normally need to quote them.  Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'.

       ! expr True if expr is false.  This character will also usually need protection from interpretation by the shell.
              找出/home下不是以.txt结尾的文件
              find /home ! -name "*.txt"

       -not expr
              Same as ! expr, but not POSIX compliant.

       expr1 expr2
              Two expressions in a row are taken to be joined with an implied "and"; expr2 is not evaluated if expr1 is false.

       expr1 -a expr2
              Same as expr1 expr2.

       expr1 -and expr2
              Same as expr1 expr2, but not POSIX compliant.

       expr1 -o expr2
              Or; expr2 is not evaluated if expr1 is true.
              或;如果expr1为真,则不计算expr2。
              ubuntu@ip-172-31-3-107:~$ find . -name "h*.txt" -o -name "w*.txt"

              当前目录及子目录下查找所有以.txt和.pdf结尾的文件
              find . \( -name "*.txt" -o -name "*.pdf" \)
              或
              find . -name "*.txt" -o -name "*.pdf" 


       expr1 -or expr2
              Same as expr1 -o expr2, but not POSIX compliant.

       expr1 , expr2
              List;  both  expr1  and expr2 are always evaluated.  The value of expr1 is discarded; the value of the list is the value of expr2.  The comma operator can be useful for searching for several different types of thing, but
              traversing the filesystem hierarchy only once.  The -fprintf action can be used to list the various matched items into several different output files.

       Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o.  This means that find . -name afile -o -name bfile -print
       will never print afile.

10、UNUSUAL FILENAMES特殊文件名

Many of the actions of find result in the printing of data which is under the control of other users.  This includes file names, sizes, modification times and so forth.  File names are a potential problem since they can contain
       any character except `\0' and `/'.  Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals).  Unusual charac‐
       ters are handled differently by various actions, as described below.

       -print0, -fprint0
              Always print the exact filename, unchanged, even if the output is going to a terminal.

       -ls, -fls
              Unusual characters are always escaped.  White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"').  Other unusual characters are printed using an octal escape.  Other
              printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is.

       -printf, -fprintf
              If the output is not going to a terminal, it is printed as-is.  Otherwise, the result depends on which directive is in use.  The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under  control  of
              files'  owners,  and so are printed as-is.  The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to
              the terminal, and so these are printed as-is.  The directives %f, %h, %l, %p and %P are quoted.  This quoting is performed in the same way as for GNU ls.  This is not the same quoting mechanism as the one  used  for  -ls
              and  -fls.   If  you  are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters.
              The setting of the `LC_CTYPE' environment variable is used to determine which characters need to be quoted.

       -print, -fprint
              Quoting is handled in the same way as for -printf and -fprintf.  If you are using find in a script or in a situation where the matched files might have arbitrary names,  you  should  consider  using  -print0  instead  of
              -print.

       The -ok and -okdir actions print the current filename as-is.  This may change in a future release.

11、EXAMPLES例子

   find /tmp -name core -type f -print | xargs /bin/rm -f

   Find files named core in or below the directory /tmp and delete them.  Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces.

   find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f

   Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled.  The -name test
   comes before the -type test in order to avoid having to call stat(2) on every file.

   find . -type f -exec file '{}' \;

   Runs `file' on every file in or below the current directory.  Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation.  The semicolon is similarly  protected  by
   the use of a backslash, though single quotes could have been used in that case also.

   find / \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \
   \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \)

   Traverse the filesystem just once, listing setuid files and directories into /root/suid.txt and large files into /root/big.txt.

   find $HOME -mtime 0

   Search  for  files  in your home directory which have been modified in the last twenty-four hours.  This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is dis‐
   carded.  That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago.

   find /sbin /usr/sbin -executable \! -readable -print

   Search for files which are executable but not readable.

   find . -perm 664

   Search for files which have read and write permission for their owner, and group, but which other users can read but not write to.  Files which meet these criteria but have other permissions bits set (for example if someone can
   execute the file) will not be matched.

   find . -perm -664

   Search  for  files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit).  This will match a
   file which has mode 0777, for example.

   find . -perm /222

   Search for files which are writable by somebody (their owner, or their group, or anybody else).

   find . -perm /220
   find . -perm /u+w,g+w
   find . -perm /u=w,g=w

   All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form.  These commands all search for files which are writable by  either  their
   owner or their group.  The files don't have to be writable by both the owner and group to be matched; either will do.

   find . -perm -220
   find . -perm -g+w,u+w

   Both these commands do the same thing; search for files which are writable by both their owner and their group.

   find . -perm -444 -perm /222 ! -perm /111
   find . -perm -a+r -perm /a+w ! -perm /a+x

   These  two  commands  both  search for files that are readable for everybody ( -perm -444 or -perm -a+r), have at least one write bit set ( -perm /222 or -perm /a+w) but are not executable for anybody ( ! -perm /111 and ! -perm
   /a+x respectively).

   cd /source-dir
   find . -name .snapshot -prune -o \( \! -name *~ -print0 \)|
   cpio -pmd0 /dest-dir

   This command copies the contents of /source-dir to /dest-dir, but omits files and directories named .snapshot (and anything in them).  It also omits files or directories whose name ends in ~, but not their contents.   The  con‐
   struct  -prune  -o  \( ... -print0 \) is quite common.  The idea here is that the expression before -prune matches things which are to be pruned.  However, the -prune action itself returns true, so the following -o ensures that
   the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant).  The expression on the right hand side of  the
   -o  is  in parentheses only for clarity.  It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them.  Because the default `and' condition between tests binds more tightly than -o,
   this is the default anyway, but the parentheses help to show what is going on.

   find repo/ -exec test -d {}/.svn \; -or \
   -exec test -d {}/.git \; -or -exec test -d {}/CVS \; \
   -print -prune

   Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots:

   repo/project1/CVS
   repo/gnu/project2/.svn
   repo/gnu/project3/.svn
   repo/gnu/project3/src/.svn
   repo/project4/.git

   In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because  we  already  found  project3/.svn),  but  ensures  sibling  directories
   (project2 and project3) are found.

猜你喜欢

转载自blog.csdn.net/uotail/article/details/88105836