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!"
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容