在實際工作中我們經常會遇到一種場景,就是明確某個文件的內容中包含某個字符串,但是忘記了這是哪個文件或者都有哪些文件符合這種情況,所以總結了幾種常用的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!"