我如何在其文件内容中找到包含一个特定的文本序列的所有文件?

下一个不起作用. 它似乎显示系统中的每个单一文件。

find / -type f -exec grep -H 'text-to-find-here' {} \;

当前回答

找到与 xargs 是优先的,当有许多潜在的比赛可以通过. 它运行比其他选项更慢,但它总是工作. 正如一些发现,xargs 不处理文件与嵌入空间默认。

这里是 @RobEarl 的答案,增强,以便处理文件与空间:

find / -type f | xargs -d '\n' grep 'text-to-find-here'

下面是 @venkat 的答案,同样增强:

find . -name "*.txt" | xargs -d '\n' grep -i "text_pattern"

这里是 @Gert van Biljon的答案,同样增强:

find . -type f -name "*.*" -print0 | xargs -d '\n' --null grep --with-filename --line-number --no-messages --color --ignore-case "searthtext"

以下是 @LetalProgrammer 的答案,同样增强:

alias ffind find / -type f | xargs -d '\n' grep

这里是 @Tayab Hussain的答案,同样增强:

find . | xargs -d '\n' grep 'word' -sl

其他回答

如果您在 Git 存储库中,您可以使用:

git grep something
grep "text-to-find-here" file_name

grep "text-to-find-here" directory_path/*

如果你想搜索当前的目录:

grep "text-to-find-here" *

希望这就是帮助......

要在输出中提供更多信息,例如,在文件中获取字符号,文本可以如下:

find . -type f -name "*.*" -print0 | xargs --null grep --with-filename --line-number --no-messages --color --ignore-case "searthtext"

如果您有一个想法,文件类型是什么,您可以通过指定文件类型扩展来缩小您的搜索,在此情况下,.pas 或.dfm 文件:

find . -type f \( -name "*.pas" -o -name "*.dfm" \) -print0 | xargs --null grep --with-filename --line-number --no-messages --color --ignore-case "searchtext"

以下是选项的简短解释:

在搜索中,从当前目录中指定 - 名称“**” : 所有文件( - 名称“*.pas” -o - 名称“*.dfm” ) : 只有 *.pas 或 *.dfm 文件, 或 与 -o -type f 指定, 您正在寻找文件 -print0 和 -null 是关键的, 将文件名从搜索中转移到嵌入在 xargs 的文件名, 允许通过文件名。

要搜索字符串和输出,就是与搜索字符串相同的字符串:

for i in $(find /path/of/target/directory -type f); do grep -i "the string to look for" "$i"; done

吉:

for i in $(find /usr/share/applications -type f); \
do grep -i "web browser" "$i"; done

要显示包含搜索字符串的文件名:

for i in $(find /path/of/target/directory -type f); do if grep -i "the string to look for" "$i" > /dev/null; then echo "$i"; fi; done;

吉:

for i in $(find /usr/share/applications -type f); \
do if grep -i "web browser" "$i" > /dev/null; then echo "$i"; \
fi; done;

我认为值得提到你如何找到:

所有包含至少一个文本的文件,其中包括大量的文本:

grep -rlf ../patternsFile.txt .

出口:

./file1  
./file2
./file4

上述,由每个文本组成:

cat ../patternsFile.txt | xargs -I{} sh -c "echo {}; grep -rl \"{}\" ."

出口:

pattern1
./file1  
./file2
pattern2
./file1  
./file4
pattern3
./file1  
./file2
./file4

请注意,为了不匹配模式File.txt本身,您需要添加一个目录(如上面的示例所示)。