3

I have a set of PDFs, and I am running

strings * | grep message

This returns the strings containing that method, is there anyway I can get grep to tell me which file it is from?

3 Answers 3

4

With GNU strings, use

strings --print-file-name -- *

to get the results prefixed by the file name (like grep).

5
  • 1
    As a note, this will also cause grep to match file names that match your pattern. Commented May 21, 2013 at 9:21
  • Yes, I know. Unless one uses particularly weird file names, one can fix that by strings --print-file-name * | grep ': message' (the file names output by strings are terminated by : ). The main question is whether the OP wants just the file names (then using grep -l only is better), or whether he also wants the matched strings (then grep will either complain about binary garbage, or output binary garbage, and none of these is helpful). Commented May 21, 2013 at 9:31
  • Correction: If the pattern "message" can occur anywhere in the string, strings --print-file-name * | grep ': .*message' is better. Commented May 21, 2013 at 9:44
  • (assuming there's no file named foo: message for instance) Commented May 21, 2013 at 10:25
  • That was one of the two things I meant when I talked about "particularly weird file names". (The other one is newlines in file names.) Commented May 21, 2013 at 10:30
1

grep has no idea where the strings came from when using this method, because it never sees the filenames. If you want the filenames, use -l and pass the glob to grep directly:

grep -l message ./*
4
  • 1
    Note that you need an implementation of grep like GNU grep that supports reading binary files. Commented May 21, 2013 at 9:59
  • What implementation doesn't support --? It would not be POSIX, and I seriously doubt any pre-POSIX implementation would support binary file. Commented May 21, 2013 at 10:23
  • @StephaneChazelas If I recall correctly, Plan 9. Commented May 21, 2013 at 16:10
  • @StephaneChazelas Nope, I'm mistaken, Plan 9 supports --. I just tested. Commented May 21, 2013 at 16:19
1

With GNU grep, you can do:

grep -Hobae '[[:print:]]*message[[:print:]]*' -- *

That will tell you the filename and offset within the file of every printable string containing message.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.