grep 尋找檔案內容但回傳檔案名

grep 尋找檔案內容但回傳檔案名

我需要 GREP 語法來完成以下任務(在 LINUX 作業系統中):

查詢 CURRENT 目錄中包含 STRING 的所有文件,但僅列出包含符合項目的 FILENAMES。

謝謝!

答案1

您可以使用

grep -rl stringToSearch .

或者

 find . -type f -exec grep -l stringToSearch {} \;

有關grep其他 UNIX 命令的更多信息,請參閱手冊 ( man)

在那種情況下man grep

-l, --files-with-matches 禁止正常輸出;相反,列印通常會列印輸出的每個輸入檔案的名稱。
掃描將在第一個匹配處停止。

顯然,作為 bash 命令,如果您的字串包含特殊字元或空格,您必須(按順序)轉義它們和/或用配額包圍您的字串

答案2

“Grep -l”將為您提供檔案名稱清單。

> echo "hello" > test_file1.list
> echo "hello2.." > test_file2.list
> echo "xyz" > test_file3.list


> grep "hello" test_file*list

test_file1.list:hello
test_file2.list:hello2..


> grep -l "hello" test_file*list
test_file1.list
test_file2.list

相關內容