1. 前言
本文主要讲解如何在 Linux 系统下使用命令行工具模糊查找文件, 本文的工具包括 find 命令的用法也介绍 grep 命令的使用方法, 同时也有 find 与 grep 两者结合, 能更精确根据条件查找文件.
2. 根据文件名模糊查找文件
例如:
在目录 / var/zcwyou 里, 找到. txt 后缀的文件, 文件名大小写敏感. 即只能匹配. txt 后缀的
[root@zcwyou ~]# find /var/zcwyou -name '*.txt'
在目录 / var/zcwyou 里, 找到. txt 后缀的文件, 忽略大小定. 即可以匹配. txt 后缀, 也可以匹配. Txt 后缀, 也可以匹配. TXT 后缀的文件.
[root@zcwyou ~]# find /var/zcwyou -iname '*.txt'
3. 根据文件名和文件内容模糊查找文件
使用方法:
结合 find 命令与 xargs 和 grep -i '目标匹配关键字'
案例 1:
在当前目录搜索文件内容含有某字符串 (大小写敏感) 的文件:
语法:
find /etc/ -type f | xargs grep '目标关键词'
案例 2:
在 / etc / 目录下, 查找带 zcwyou 关键词的文件
[root@zcwyou ~]# find /etc/ -type f | xargs grep 'zcwyou'
可以找到以下文件和文件对应的内容:
- /etc/group-:zcwyou:x:1000:
- /etc/gshadow-:zcwyou:!!::
- /etc/passwd-:zcwyou:x:1000:1000:zcwyou:/home/zcwyou:/bin/bash
- /etc/group:zcwyou:x:1000:zcwyou
- /etc/shadow-:zcwyou:
是不是非常高效?
案例 3:
在当前目录搜索文件内容含有某字符串 (忽略大小写) 的特定文件:
借用 find 命令查找当前目录下所有以. c 后缀结尾的文件和子目录里以. c 后缀结尾的文件, 并把结果以参数形式传递给 grep, 由 grep 进行搜索和过滤.
[root@zcwyou ~]#find . -type f -name '*.c' | xargs grep -i '目标搜索关键词'
4. 使用 `find` 命令模糊查找 Linux 文件
在当前目录下, 模糊查找在系统中最后 10 分钟访问的文件
[root@zcwyou ~]# find . -amin -10
在当前目录下, 模糊查找在系统中最后 48 小时访问的文件
[root@zcwyou ~]# find . -atime -2
在当前目录下, 查找在系统中为空的文件或者文件夹
[root@zcwyou ~]# find . -empty
在当前目录下, 查找在系统中属于 group cat 的文件
[root@zcwyou ~]# find . -group cat
模糊查找在系统中最后 5 分钟里修改过的文件
[root@zcwyou ~]# find . -mmin -5
查找在系统中最后 24 小时里修改过的文件
[root@zcwyou ~]# find . -mtime -1
5. 根据用户属性模糊查找 Linux 文件
查找在系统中属于作废用户的文件
[root@zcwyou ~]# find . -nouser
查找在系统中属于 zcwyou 这个用户的文件
[root@zcwyou ~]# find . -user zcwyou
6. 通过文件大小模糊查找文件
查找根目录下超过 1M 的文件, 并打印
[root@zcwyou ~]# find / -size +1M -type f -print
查找当前目录下等于 500 字节的文件, 包括子目录, 并打印结果
[root@zcwyou ~]# find -size 500c -print
查找 home 目录下小于 600k 的文件
[root@zcwyou ~]# find /home -size -600k -print
7. 通过文件新旧查找文件
查找比 old.txt 新的文件
[root@zcwyou ~]# find -newer "old.txt" -type f -print
查找比 newer.txt 旧的文件
[root@zcwyou ~]# find ! -newer "newer.log" -type f -print
查找比 old.txt 新, 比 newer.txt 旧的文件
[root@zcwyou ~]# find -newer 'old.txt' ! -newer 'newer.txt' -type f -print
来源: http://os.51cto.com/art/201908/602096.htm