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!"
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容