8

How do I get unix to search inside ALL files for a the string "hello"?

I've tried the following but it doesn't work:

sudo grep "hello" | find / -name "*" 2>/dev/null

Does anyone have any other ideas?

Thank you.

3 Answers 3

28

Maybe this one?

sudo cd / && grep -rn "hello" *

EDIT: the 'n' option of course is not needed - it simply displays the line numbers and I find it nice. The 'r' option tells grep to perform recursive search within directories.

Sign up to request clarification or add additional context in comments.

4 Comments

Specifying . may be preferable over * if there are a lot of files in the directory. (You can hit a too many arguments error)
@NBenatar thought about this solution but I think this solution is a bit easier to understand. Could be that I am wrong.
@izomorphius: You have three bugs. First, cd will be executed with sudo and switch to /, but grep wont be executed as the sudo'd user (IOW, not as root). Second, because cd / was in another shell the actual working directory won't change and grep will not run in / (unless / was the working directory already, in which case why cd?). Thirdly, grep -r '' * will not search all files since * will not expand hidden files and directories (those with a leading .) unless shopt -s dotglob is in effect (bash only).
how would I do this but just search .html files?
12

Use

grep -r 'pattern' /

If your grep supports -r, (GNU grep does); if not use

find / -type f -exec grep 'pattern' {} +

If your find supports -exec with +, otherwise use

find / -type f -printf '%p\0' | xargs -0 grep 'pattern'

If your find supports -printf and your xargs supports -0, or

find / -type f -print0 | xargs -0 grep 'pattern'

If your find supports only -print0 and your xargs supports -0. In all other cases fall back on

find / -type f | xargs grep 'pattern'

This is maximally compatible, with the caveat that certain unusual file names will fail to be grepped and crafted file names could pose a security risk.

Note that you will have to be root in order to be sure of searching all files and that the search will be case-sensitive unless you add -i to grep.

1 Comment

find / -type f | xargs grep 'pattern' ==> works for aix!
2

This?

find . -exec grep -H "hello" {} \;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.