zoukankan      html  css  js  c++  java
  • Linux中find命令的用法举例

    前言

    find是Linux系统中最重要和最常用的命令之一,它可以根据不同的条件来查找文件,例如权限、拥有者、修改日期/时间、文件大小等等。

    其基本语法如下:

    $ find [path] [option] [expression]
    

    下面我来总结一下自己常用的一些用法和例子

    find用法举例

    基本用法

    列出当前目录和子目录下的所有文件

    $ find
    $ #等同于 find .
    

    查找特定目录下的文件

    $ #list all files under $HOME dir.
    $ find $HOME
    

    查找特定文件名的文件

    使用 -name选项来查找特定文件名的文件

    $ #list all files(or sub directories) whose filename starts with `test_` under $HOME dir.
    $ find $HOME -name "test_*" 
    $# list out all .py files under $HOME
    $ find $HOME -name "*.py"
    

    如果要忽略大小写,则使用 -iname 选项,而不是 -name 选项。

    $ find $HOME -iname "*.Csv"
    
    $ #list all files(or sub directories) whose filename starts with `test_` under $HOME dir with maxdepth=1 mindepth =1 .
    $ find $HOME -name "test_*"  -maxdepth 1 -mindepth 1 
    

    查找特定的文件类型

    我们可以用 -type 来指定需要查找的文件类型,例如

    • -type f 用来查找文件,
    • -type d 用来查找文件夹/目录
    $ find $HOME -type f -name "test_"
    

    在多个目录下查找

    指定多个目录路径即可

    $ find $HOME /tmp -type f -name "test_"
    

    反向查找

    我们可以用 not 或者 !(感叹号) 来表达一个 “”的逻辑,用来查找不满足条件的所有文件。

    #list out all files that are not .txt 
    $ find $HOME -not -name "*.txt"
    

    进阶用法

    限制目录查找的深度

    find 命令默认会递归查找整个目录树,而这非常消耗时间和资源。我们可以通过设定 -maxdepth 和 ==-mindepth 选项来限制目录查找的深度的范围。

    查找指定权限的文件

    我们可以通过指定 -perm 选项来查找具有特定权限的文件。下面的示例中查找了所有具有 0755 权限的文件

    $ find . -type f -perm 0755
    

    查找只读文件

    $ find . -type f -perm /u=r
    

    查找可执行文件

    $ find . -type f -perm /a=x
    

    基于文件拥有者和用户组的查找

    我们可以使用 -user 和 -group 选项来指定查找文件的特定owner和group

    $ find . -user lestat -staff
    

    基于日期和时间的查找

    我们还可以基于日期和时间进行查找。例如我们想查找出去一些旧文件时,我们就可以使用这个选项。

    与时间相关的选项有 –amin, -atime, -cmin, -ctime, -mmin, -mtime
    它们之间的差别可以参考What-is-the-difference-between-mtime-atime-and-ctime

    查找 N 天之内修改过的文件

    $ find $HOME -mtime 7
    

    查找 N 天之内被访问过的文件

    $ find $HOME -atime -7
    

    查找某段时间范围内被修改过内容的文件

    $ find $HOME -mtime +5 -mtime -10
    

    查找过去的 N 分钟内状态发生改变的文件

    $ find $HOME -cmin -60
    

    查找过去的 1 小时内被修改过内容的文件

    $ find $HOME -mmin -60
    

    基于文件大小的查找

    查找指定大小的文件

    $ find $HOME -size 50M
    

    查找大小在一定范围内的文件

    $ find $HOME -size +50M -size -100M
    

    找出空文件

    $ find $HOME  -type f -empty
    

    高级操作 TO-DO

    find 命令不仅可以通过特定条件来查找文件,还可以对查找到的文件使用任意linux命令进行操作, 例如 lsmvrm

    find + ls

    $ find $HOME -exec ls -ld {} ;
    

    find + mv

    $ find $HOME name "tmp_*" -exec mv -t /tmp {} +
    

    find + rm

    $ find $HOME -name "tmp_*" -exec rm -r -f {} ;
    

    参考来源

    35-practical-examples-of-linux-find-command/

  • 相关阅读:
    iftop 安装流程
    Centos 6.5 Tengine 安装流程
    linux 查看系统进程前十
    Centos 6.5 mongodb 安装流程
    linux 磁盘查看方式
    Linux 磁盘分区及挂载
    linux 路由添加
    rsyslog 重启
    文件上传到Web服务器
    一些链接1
  • 原文地址:https://www.cnblogs.com/lestatzhang/p/10611312.html
Copyright © 2011-2022 走看看