今天用到一个grep和find的组合用法,用来查找某个目录下含有指定字符串的文件及位置
`find {dir} -type f | xargs grep “{content}”
通常使用文件类型为筛选条件,因为文件名常为未知
eg:find /usr/local/ -type f | xargs grep "account"
以下对find和grep做一些补充用法
find
find常用来查找含有指定特征的文件,接下来列举常用的几种查找方式
按文件名来查找
find {dir} -name “{name}”
在dir目录下遍历文件名为name的文件,其中name可以使用正则匹配
eg: find /opt/ -name "*.log"
按文件类型查找
find {dir} -type {b/d/c/p/l/f}
在dir目录下遍历文件类型为块设备/目录/字符设备/管道/符号链接/普通文件
eg: find /opt/ -type f
按文件最后更改时间来查找
find {dir} -mtime {-n/+n}
在dir目录下查找最后更改时间为n天以内(-n)或最后更改时间为n天以前的文件
按文件创建时间来查找文件
find {dir} -ctime {-n/+n}
在dir目录下查找创建时间为n天以内(-n)或创建时间为n天以前的文件
eg:find /opt/ -ctime +10
按访问时间来查找文件
find {dir} -atime {-n/+n}
在dir目录下查找最后访问时间为n天以内(-n)或最后访问时间为n天以前的文件
eg:find /opt/ -atime -3
按文件属主来查找文件
find {dir} -user {username}
eg:find / -user nginx
查找无有效属主的文件
即文件的属主在/ec/passwd/中不存在
find {dir} -nouser
eg:find /opt/ -nouser
按文件大小查找文件
find {dir} -size {n}
查找文件大小为n字节的文件
eg:find /opt/ -size 100
忽略某个目录
假设/opt/
目录下有三个目录ceshi1
,ceshi2
,ceshi3
,里面都有一个a文件
[root@localhost ~]# find /opt/ -type f -name a -print
/opt/ceshi2/a.txt
/opt/ceshi3/a.txt
/opt/ceshi1/a.txt
要忽略ceshi1
目录:
[root@localhost ~]# find /opt/ -path /opt/ceshi1 -prune -o -name a.txt -print
/opt/ceshi2/a.txt
/opt/ceshi3/a.txt
./a
不能写成./a/
,否则没有作用。-o
是-or
的意思,也必须加
[root@localhost ~]# find /opt/ -path /opt/ceshi1/ -prune -o -name a.txt -print
find: warning: -path /opt/ceshi1/ will not match anything because it ends with /.
/opt/ceshi2/a.txt
/opt/ceshi3/a.txt
/opt/ceshi1/a.txt