查找Linux所有目录下的指定文件名,Linux查找指定目录下包含指定字符串的所有文件...

在实际工作中我们经常会遇到一种场景,就是明确某个文件的内容中包含某个字符串,但是忘记了这是哪个文件或者都有哪些文件符合这种情况,所以总结了几种常用的Linux下查找指定目录下包含指定字符串的所有文件的方法。

示例(假设文件存在于下方目录下):

test-find/test.txt

test.txt中的内容如下

"No system is safe!"

查找test-find目录下包含"system"字符串的所有文件

【方式1】

grep -r "system"

查询结果如下:

[work@recurrent ~]$ grep -r "system" test-find/

test-find/test.txt:"No system is safe!"

如果想要显示字符串具体在哪一行怎么办呢

grep -rn "system"

效果如下:

[work@recurrent ~]$ grep -rn "system" test-find/

test-find/test.txt:1:"No system is safe!"

可以看到“No system is safe”前多了一个":1",即文件的第一行

【方式2】

find test-find/ | xargs grep "system"

效果如下

test-find/test.txt:"No system is safe!"

【方式3】

find test-find/ | xargs grep -ri "system"

效果如下:

test-find/test.txt:"No system is safe!"

test-find/test.txt:"No system is safe!"

如果不想显示文件内容,只显示文件名,可以在grep后增加-l参数

find test-find/ | xargs grep -ri "system" -l

效果如下:

test-find/test.txt

test-find/test.txt

【方式4】(可指定文件类型)

find test-find/ -type f -name "*.txt" | xargs grep "system"

效果如下:

"No system is safe!"

如果指定了一个不存在的文件类型会怎样呢

find test-find/ -type f -name "*.pdf" | xargs grep "system"

效果如下:

[work@recurrent ~]$

终端打印为空

【其他】

现在我们在文件夹下多创建几个文件,看一下多文件时的效果

ll

总用量 28

-rw-rw-r-- 1 work work 21 1月 17 15:44 test1.txt

-rw-rw-r-- 1 work work 21 1月 17 15:44 test2.txt

-rw-rw-r-- 1 work work 21 1月 17 15:44 test3.txt

-rw-rw-r-- 1 work work 21 1月 17 15:45 test4.txt

-rw-rw-r-- 1 work work 21 1月 17 15:45 test5.txt

-rw-rw-r-- 1 work work 21 1月 17 15:45 test6.txt

-rw-rw-r-- 1 work work 21 1月 17 15:09 test.txt

效果如下;

[work@recurrent ~]$ grep -rn "system" test-find/

test-find/test4.txt:1:"No system is safe!"

test-find/test3.txt:1:"No system is safe!"

test-find/test2.txt:1:"No system is safe!"

test-find/test1.txt:1:"No system is safe!"

test-find/test5.txt:1:"No system is safe!"

test-find/test6.txt:1:"No system is safe!"

test-find/test.txt:1:"No system is safe!"

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值