Shell命令列出找到匹配项的文件名

时间:2018-06-29 09:08:41

标签: shell grep pipe

我正在尝试搜索二进制文件列表以在Mac上找到一些关键字。

以下方法可以列出所有匹配项,但不会向我显示在其中找到文件的列表:

find . -type f -exec strings {} \;|grep "Bv9qtsZRgspQliITY4"

有什么窍门吗?

5 个答案:

答案 0 :(得分:1)

-exec与“'脚本”一起使用:

find . -type f \
       -exec sh -c 'strings "$1" | grep -q "Bv9qtsZRgspQliITY4"' -- {} \; \
       -print

上面将打印所有匹配文件的路径。如果您还想打印匹配项,可以使用:

find . -type f \
       -exec sh -c 'strings "$1" | grep "Bv9qtsZRgspQliITY4"' -- {} \; \
       -print

但是,这将在匹配项后 打印路径。如果不希望这样做,则可以使用:

find . -type f \
       -print \
       -exec sh -c 'strings "$1" | grep "Bv9qtsZRgspQliITY4"' -- {} \;

另一方面,这将打印所有路径,甚至是不匹配的路径。要仅打印 个匹配路径及其匹配项,请执行以下操作:

find . -type f \
       -exec sh -c 'strings "$1" | grep -q "Bv9qtsZRgspQliITY4"' -- {} \; \
       -print \
       -exec grep "Bv9qtsZRgspQliITY4" {} \;

这将在匹配文件上grep运行两次,这会使它变慢。如果这是一个问题,则可以将匹配项存储在变量中,并且如果先打印任何路径,然后再匹配。这留给读者练习。 *

*让我知道是否应该在此处发布。

答案 1 :(得分:-1)

尝试grep -rl "Bv9qtsZRgspQliITY4" .

选项说明:

  • -r:递归搜索
  • -l:不打印文件内容,仅打印文件名。

(可选)您可能希望使用-i进行不区分大小写的搜索。

您的想法存在问题,您正在将strings的输出传递到grep中。文件名仅传递给strings,这意味着strings之后的所有内容都不知道文件名。

答案 2 :(得分:-1)

我不太确定可移植性,但是如果您使用的是GNU版本的grep,则可以使用--files-with-matches

-l, --files-with-matches  print only names of FILEs containing matches

然后您可以使用类似这样的内容:

grep --recursive --files-with-matches "Bv9qtsZRgspQliITY4" *

答案 3 :(得分:-1)

您可以使用

# this will list all the files containing given text in current directory
# i to ignore case
# l to list files with matches
# R read and process all files in that directory, recursively, following all symbolic links
grep -iRl "your-text-to-find" ./

# for case sensitive search
grep -Rl "your-text-to-find" ./

答案 4 :(得分:-1)

好吧,如果仅用于打印文件名,请不要使用find而是grep。

grep -ar . -e 'soloman' ./testo.txt:1:soloman
  • -a:在二进制文件中搜索
  • -r:递归

并保持简单。

如果您不想在输出中看到匹配的单词,只需添加-l, --files-with-matches

user@DESKTOP-RR909JI ~/projects/search
$ grep -arl . -e 'soloman'
./testo.txt
相关问题