Linux中利用grep和find查找文件内容

今天用到一个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


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值