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?


With GNU strings, use

strings --print-file-name -- *

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

  • 1
    As a note, this will also cause grep to match file names that match your pattern. – Chris Down May 21 '13 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). – Uwe May 21 '13 at 9:31
  • Correction: If the pattern "message" can occur anywhere in the string, strings --print-file-name * | grep ': .*message' is better. – Uwe May 21 '13 at 9:44
  • (assuming there's no file named foo: message for instance) – Stéphane Chazelas May 21 '13 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.) – Uwe May 21 '13 at 10:30

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 ./*
  • 1
    Note that you need an implementation of grep like GNU grep that supports reading binary files. – Stéphane Chazelas May 21 '13 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. – Stéphane Chazelas May 21 '13 at 10:23
  • @StephaneChazelas If I recall correctly, Plan 9. – Chris Down May 21 '13 at 16:10
  • @StephaneChazelas Nope, I'm mistaken, Plan 9 supports --. I just tested. – Chris Down May 21 '13 at 16:19

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.