我如何在其文件内容中找到包含一个特定的文本序列的所有文件?
下一个不起作用. 它似乎显示系统中的每个单一文件。
find / -type f -exec grep -H 'text-to-find-here' {} \;
我如何在其文件内容中找到包含一个特定的文本序列的所有文件?
下一个不起作用. 它似乎显示系统中的每个单一文件。
find / -type f -exec grep -H 'text-to-find-here' {} \;
当前回答
grep "text-to-find-here" file_name
或
grep "text-to-find-here" directory_path/*
如果你想搜索当前的目录:
grep "text-to-find-here" *
其他回答
我写了一个Python脚本,它做了一些类似的事情,这就是如何使用这个脚本。
./sniff.py path pattern_to_search [file_pattern]
第一個論點,路径,是我們將重新搜尋的目錄. 第二個論點, pattern_to_search,是一個常見的表現,我們想要在檔案中搜尋。
第三个论点, file_pattern,是可选的. 这是另一个常见的表达式,在一个文件名上工作. 只有与这个常见的表达式相匹配的文件将被考虑。
例如,如果我想搜索Python文件的扩展Py包含Pool(跟随“Adaptor”这个词,我做以下,
./sniff.py . "Pool(.*?Adaptor" .*py
./Demos/snippets/cubeMeshSigNeur.py:146
./Demos/snippets/testSigNeur.py:259
./python/moose/multiscale/core/mumbl.py:206
./Demos/snippets/multiComptSigNeur.py:268
而 voila,它产生了匹配文件的路径和线号,在那里比赛被发现,如果超过一个比赛被发现,那么每个线号将添加到文件名。
我很感动如何简单的吸引力使它与“rl”:
grep -rl 'pattern_to_find' /path/where/to/find
-r to recursively find a file / directory inside directories..
-l to list files matching the 'pattern'
使用“r”而不“l”以查看文件名跟随文本中的模式!
grep -r 'pattern_to_find' /path/where/to/find
它只是完美工作......
要搜索字符串和输出,就是与搜索字符串相同的字符串:
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;
您也可以使用 awk:
awk '/^(pattern)/{print}' /path/to/find/*
模式是您想要在文件中匹配的行。
你可以使用:
grep -r "string to be searched" /path/to/dir
r 是可重复的,因此将在指定的路径和其子指南中进行搜索,这将告诉您文件名以及在文件中印刷线的字符串。
或类似于您正在尝试的命令(例如: )在所有JavaScript文件中搜索( (*.js):
find . -name '*.js' -exec grep -i 'string to search for' {} \; -print
这将打印文本显示的文件中的行,但它不会打印文件名。
除了此命令之外,我们还可以写下: grep -rn “String to search” /path/to/directory/or/file -r: recursive search n: line number will be shown for matches