I'm trying to find a way to scan my entire Linux system for all files containing a specific string of text. Just to clarify, I'm looking for text within the file, not in the file name.

When I was looking up how to do this, I came across this solution twice:

find / -type f -exec grep -H 'text-to-find-here' {} \;

However, it doesn't work. It seems to display every single file in the system.

Is this close to the proper way to do it? If not, how should I? This ability to find text strings in files would be extraordinarily useful for some programming projects I'm doing.

share|improve this question

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

8  
remember that grep will interpret any . as a single-character wildcard, among others. My advice is to alway use either fgrep or egrep. – Walter Tross Oct 28 '13 at 11:54
5  
anyway, you were almost there! Just replace -H with -l (and maybe grep with fgrep). To exclude files with certain patterns of names you would use find in a more advanced way. It's worthwile to learn to use find, though. Just man find. – Walter Tross Oct 28 '13 at 12:01
1  
find … -exec <cmd> + is easier to type and faster than find … -exec <cmd> \;. It works only if <cmd> accepts any number of file name arguments. The saving in execution time is especially big if <cmd> is slow to start like Python or Ruby scripts. – hagello Jan 28 '16 at 5:16
    
To search non-recursively in a given path the command is `grep --include=*.txt -snw "pattern" thepath/*. – Stéphane Laurent Aug 15 '16 at 12:34
    
@StéphaneLaurent I think you are complicating it too much. Just say grep "pattern" path/*.txt – fedorqui Dec 2 '16 at 13:13

38 Answers 38

up vote 5437 down vote accepted

Do the following:

grep -rnw '/path/to/somewhere/' -e 'pattern'
  • -r or -R is recursive,
  • -n is line number, and
  • -w stands for match the whole word.
  • -l (lower-case L) can be added to just give the file name of matching files.

Along with these, --exclude, --include, --exclude-dir flags could be used for efficient searching:

  • This will only search through those files which have .c or .h extensions:

    grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
    
  • This will exclude searching all the files ending with .o extension:

    grep --exclude=*.o -rnw '/path/to/somewhere/' -e "pattern"
    
  • For directories it's possible to exclude a particular directory(ies) through --exclude-dir parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:

    grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"
    

This works very well for me, to achieve almost the same purpose like yours.

For more options check man grep.

share|improve this answer
50  
use --exclude. like "grep -rnw --exclude=*.o 'directory' -e "pattern" – rakib_ Jun 6 '13 at 8:29
10  
I find grep's --include parameter very useful. For example: grep -rnw --include=*.java . -e "whatever I'm looking for" – Lucas A. Nov 14 '13 at 15:43
40  
it's worth noting: it seems the r option is lazy (traverses depth-first, than stops after the first directory), while R is greedy (will traverse the entire tree correctly). – Eliran Malka Mar 24 '15 at 15:09
9  
Note(especially for newbies): The quotation marks in the above command are important. – madD7 Dec 22 '15 at 12:37
27  
@Eliran Malka R en r will both traverse directories correctly, but R will follow symbolic links. – bzeaman Jul 5 '16 at 8:36

find with xargs is preferred when there are many potential matches to sift through. It runs more slowly than other options, but it always works. As some have discovered,xargs does not handle files with embedded spaces by default. You can overcome this by specifying the -d option.

Here is @RobEarl's answer, enhanced so it handles files with spaces:

find / -type f | xargs -d '\n' grep 'text-to-find-here'

Here is @venkat's answer, similarly enhanced:

find . -name "*.txt" | xargs -d '\n' grep -i "text_pattern"

Here is @Gert van Biljon's answer, similarly enhanced:

find . -type f -name "*.*" -print0 | xargs -d '\n' --null grep --with-filename --line-number --no-messages --color --ignore-case "searthtext"

Here is @LetalProgrammer's answer, similarly enhanced:

alias ffind find / -type f | xargs -d '\n' grep

Here is @Tayab Hussain's answer, similarly enhanced:

find . | xargs -d '\n' grep 'word' -sl
share|improve this answer

If you know the extension of your source files (and the project is not too big), use:

grep "class foo" **/*.c

within the folder of your interest.

The magic here is by using globbing option (**) which helps you to scan all the files recursively with specific extension. If doesn't work, activate it by shopt -s globstar. You may also use **/*.* for all files (excluding hidden and without extension).

Add the following useful parameters (most common for source code searching):

  • -i - for insensitive searching,
  • -w - to search for a words (in opposite of partial word matching),
  • -n - for showing the line of your match,
  • --context=5 - to increase context, so you recognise surrounding code better,
  • -color - mark up the matching text with color (sometimes it works by default),
  • -I - to ignore binary files (which by specifying file extension, you actually do).

If you've the error that your argument is too long, consider narrowing down your search, or use find syntax instead.

share|improve this answer
1  
I also find extended globbing useful. But keep in mind that if there are really huge number of files, you can get a "Argument list too long" error. (Simple globbing is also prone to this kind of error). – Yoory N. Nov 30 '17 at 6:47

grep is your good friend to achieve this.

grep -r <text_fo_find> <directory>

if you don't care about the case of the text to find then use

grep -ir <text_to_find> <directory>
share|improve this answer

List of file names containing a given text

First of all, I believe you have used -H instead of -l. Also you can try adding the text inside quotes followed by {} \.

find / -type f -exec grep -l "text-to-find-here" {} \; 

Example

Let's say you are searching for files containing specific text "Apache License" inside your directory. It will display results somewhat similar to below (output will be different based on your directory content).

bash-4.1$ find . -type f -exec grep -l "Apache License" {} \; 
./net/java/jvnet-parent/5/jvnet-parent-5.pom
./commons-cli/commons-cli/1.3.1/commons-cli-1.3.1.pom
./io/swagger/swagger-project/1.5.10/swagger-project-1.5.10.pom
./io/netty/netty-transport/4.1.7.Final/netty-transport-4.1.7.Final.pom
./commons-codec/commons-codec/1.9/commons-codec-1.9.pom
./commons-io/commons-io/2.4/commons-io-2.4.pom
bash-4.1$ 

Remove case sensitiveness

Even if you are not use about the case like "text" vs "TEXT", you can use the -i switch to ignore case. You can read further details here.

Hope this helps you.

share|improve this answer
6  
OP asked for files that contain the text in their content not filename. – Auxiliary Dec 24 '14 at 3:16
1  
Which is what this command does: find will pass all the paths it finds to the command grep -l "text-to-find-here" <file found>". You may add restrictions to the file name, e.g. find / -iname "*.txt" to search only in files which name ends in .txt – Mene Apr 20 '17 at 13:46
1  
@Auxiliary - included a sample output to avoid any confusion for the readers. – lkamal Oct 7 '17 at 5:56

I am fascinated by how simple grep makes it with 'rl'

grep -rl 'pattern_to_find' /path/where/to/find

-r to find recursively file / directory inside directories..
-l to list files matching the 'pattern'

Use '-r' without 'l' to see the file names followed by text in which the pattern is found!

grep -r 'pattern_to_find' /path/where/to/find

Works just perfect..

Hope it helps!

share|improve this answer

There is an ack tool that would do exactly what you are looking for.

http://linux.die.net/man/1/ack

ack -i search_string folder_path/*

You may ignore -i for case sensitive search

share|improve this answer
1  
What is this adding to the existing answers? This was suggested more than three years ago already. – fedorqui Dec 2 '16 at 13:20
1  
@fedorqui 1)no piping! 2)Use regular expressions 3)Get line numbers, file name with relative path, highlighted text etc. useful for editing after the search e.g "vim +lineno path/file.cpp" will get you right at the line no of interest. See the output of the command "ack include\|hpp" that searches "include" or "hpp" keywords under my search folder and subfolders. I hope the point is clear. Here is the sample output(Can't show the keyword highlights with simple text) process/child.hpp 11:boost/process/child.hpp process/all.hpp 21:#include <boost/process/execute.hpp> – Pal Jul 11 '17 at 15:57

As Peter in the previous answer mentioned, all previous answers suggest grep and find.

But there is more sophisticated way using Gnome Commander with perfect GUI and with tons of options since 2001, finding files is just one of them. It is a free utility as well proven by time.

share|improve this answer

All previous answers suggest grep and find. But there is another way: Use midnight commander

It is a free utility (30 years old, proven by time) which is visual without being GUI. Has tons of functions, finding files is just one of them.

share|improve this answer
    
ranger would be in the same idea – nilon Jul 12 '17 at 20:03

A Simple find can work handy. alias it in your ~/.bashrc file:

alias ffind find / -type f | xargs grep

Start a new terminal and issue:

ffind 'text-to-find-here'
share|improve this answer

You can use the following commands to find particular text from a file:

cat file | grep 'abc' | cut -d':' -f2
share|improve this answer
    
the question is about finding which files contain a string, not about finding a string in a file. – fedorqui Nov 6 '17 at 10:40

Use:

grep -c Your_Pattern *

This will report how many copies of your pattern are there in each of the files in the current directory.

share|improve this answer

Silver Searcher is a terrific tool, but ripgrep may be even better.

It works on Linux, Mac and Windows, and was written up on Hacker News a couple of months ago (this has a link to Andrew Gallant's Blog which has a GitHub link):

Ripgrep – A new command line search tool

share|improve this answer

There's a new utility called The Silversearcher

sudo apt install silversearcher-ag

It works closely with Git and other VCS. So you won't get anything in a .git or another directory.

You can simply use

ag -ia "Search query"

And it will do the task for you!

share|improve this answer
3  
ag is awesome. A must have. – fmquaglia Nov 27 '16 at 14:11

Try this:

find / -type f -name "*" -exec grep -il "String_to_search" {} \;

Or

for i in /*;do grep -Ril "String_to_search" $i;done 2> /dev/null
share|improve this answer
    
what is this adding to the existing answers? – fedorqui Dec 2 '16 at 13:19
    
Good Question - Let start with top answers to this question. I tried below commands on AIX server with more than 15k files in log dir. grep -rnw '/path/to/somewhere/' -e "pattern" >>> got the error "/usr/bin/grep: 0403-027 The parameter list is too long." grep -Ril "text-to-find-here" / >>> got the error "/usr/bin/grep: 0403-027 The parameter list is too long." ack 'text-to-find-here' >>> got the error "Segmentation fault(coredump)" – VIPIN KUMAR Dec 2 '16 at 17:07
    
find / -type f -name "" -exec grep -il "String_to_search" {} \; >>> It will produce the result with filename and file data. find / -type f -exec grep -H 'text-to-find-here' {} \; >>> It will produce the result with filename only. for i in /;do grep -Ril "String_to_search" $i;done 2> /dev/null >>> It will work like grep -Ril "text-to-find-here" / but support large number of file. – VIPIN KUMAR Dec 2 '16 at 17:07

Hope this is of assistance...

Expanding the grep a bit to give more information in the output, for example, to get the line number in the file where the text is can be done as follows:

find . -type f -name "*.*" -print0 | xargs --null grep --with-filename --line-number --no-messages --color --ignore-case "searthtext"

And if you have an idea what the file type is you can narrow your search down by specifying file type extensions to search for, in this case .pas OR .dfm files:

find . -type f \( -name "*.pas" -o -name "*.dfm" \) -print0 | xargs --null grep --with-filename --line-number --no-messages --color --ignore-case "searchtext"

Short explanation of the options:

  1. . in the find specifies from the current directory.
  2. -name "*.*" : for all files ( -name "*.pas" -o -name "*.dfm" ) : Only the *.pas OR *.dfm files, OR specified with -o
  3. -type f specifies that you are looking for files
  4. -print0 and --null on the other side of the | (pipe) are the crucial ones, passing the filename from the find to the grep embedded in the xargs, allowing for the passing of filenames WITH spaces in the filenames, allowing grep to treat the path and filename as one string, and not break it up on each space.
share|improve this answer

Try this:

find . | xargs grep 'word' -sl
share|improve this answer
3  
this is far slower than the grep solution – amine Dec 22 '14 at 16:58

grep can be used even if we're not looking for a string.

Simply running,

grep -RIl "" .

will print out the path to all text files, i.e. those containing only printable characters.

share|improve this answer
1  
I don't see how this is better than using a mere ls or find (for the recursive) – fedorqui Dec 2 '16 at 13:15

You can use:

grep -r "string to be searched"  /path/to/dir

The r stands for recursive and so will search in the path specified and also its sub-directories. This will tell you the file name as well as print out the line in the file where the string appears.

Or a command similar to the one you are trying (example: ) for searching in all javascript files (*.js):

find . -name '*.js' -exec grep -i 'string to search for' {} \; -print

This will print the lines in the files where the text appears, but it does not print the file name.

share|improve this answer
1  
Thanx for the find version. My grep version (busybox for NAS) hasn't the -r option, i really needed another solution! – j.c Sep 2 '16 at 10:34
1  
Thank you for the 'find' version! It is so important to be able to filter by '.js' or '.txt', etc. Nobody wants to spend hours waiting for grep to finish searching all the multi-gigabyte videos from the last family vacation, even if the command is easier to type. – mightypile Aug 16 '17 at 15:10

Use pwd to search from any directory you are in, recursing downward

grep -rnw `pwd` -e "pattern"

Update Depending on the version of grep you are using, you can omit pwd. On newer versions . seems to be the default case for grep if no directory is given thus:

grep -rnw -e "pattern"

or

grep -rnw "pattern"

will do the same thing as above!

share|improve this answer
2  
using pwd is not necessary at all, since it is the default. grep -rnw "pattern" suffices. – fedorqui Dec 2 '16 at 13:17
    
and in fact the grep -rnw and similar is what was answered like three years ago, I don't see how this answer is adding value. – fedorqui Dec 2 '16 at 14:03
    
The selected answer does not show the default pattern, and 5 peoples seemed to have found it useful – mahatmanich Dec 14 '16 at 8:27
    
What do you mean with "default pattern"? The accepted answer contains grep -rnw '/path/to/somewhere/' -e "pattern" which is what you have here. 5 votes after 2.3M visits does not mean that much. – fedorqui Dec 14 '16 at 8:45
    
I agree :-) what I was missing in the original answer is the use case that you don't have to give a path at all or to search the current directory recursively which is not reflected in the accepted answer. Thus it was a good learning experience about grep to dig a bit deeper. – mahatmanich Dec 14 '16 at 14:05
grep -Erni + "text you wanna search"

The command will search recursivly in all files and directories of the current directory and print the result.

Note: if your grep output isn't colored, you can change it by using the grep='grep --color=always' alias in your shell src file

share|improve this answer

Avoid the hassle and install ack-grep. It eliminates a lot of permission and quotation issues.

apt-get install ack-grep

Then go to the directory you want to search and run the command below

cd /
ack-grep "find my keyword"
share|improve this answer
grep -insr "pattern" *
  • i: Ignore case distinctions in both the PATTERN and the input files.
  • n: Prefix each line of output with the 1-based line number within its input file.
  • s: Suppress error messages about nonexistent or unreadable files.
  • r: Read all files under each directory, recursively.
share|improve this answer
2  
Can you explain how your answer improves upon the other answers, or how it is sufficiently different from them? – Amos M. Carpenter Feb 26 '16 at 6:10
    
not much complex to remember, will cover all patterns(case-senstivity -> off, includes file-names and line number and will do recursively search etc) and using "*" in the end will search all directories (no need to specify any path or directory name). – enfinet Feb 26 '16 at 6:15
    
Sorry, I should've been clearer: it would be great if you could include that explanation in your answer. As it stands, especially with so many other similar answers already, it is hard to see from such a short answer what the benefit of trying it over the accepted answer or one of the upvoted ones would be. – Amos M. Carpenter Feb 26 '16 at 6:35
    
This is the good answer + the good explanation – Anonymous miliana Sep 22 '16 at 13:45
4  
@AmosM.Carpenter One thing I love about this answer is pointing out the suppress argument, which can help filter out noise that doesn't matter to getting the results we actually want. Grep prints errors like, "Function not implemented", "Invalid Argument", "Resource unavailable", etc. etc on certain "files". – leetNightshade Feb 20 '17 at 5:58

You can use grep -ilR:

grep -Ril "text-to-find-here" /
  • i stands for ignore case (optional in your case).
  • R stands for recursive.
  • l stands for "show the file name, not the result itself".
  • / stands for starting at the root of your machine.
share|improve this answer
8  
And what does the /* at the end stand for? All directories starting at root? – Nathan Jun 6 '13 at 8:13
46  
Based on my experience, the -i makes it slow down a lot, so don't use it if not necessary. Test it in a certain dir and then generalise. It should be completed within few minutes. I think a regular expression would make it slower. But my comments are based on suppositions, I suggest you to test it with time in front of the line. – fedorqui Jun 6 '13 at 8:14
7  
If you are not searching using a regex you can use fgrep in place of grep on most systems. – markle976 Sep 28 '13 at 14:49
6  
Yes @markle976, in fact from man grep: fgrep is the same as grep -F -> Interpret PATTERN as a list of fixed strings. – fedorqui Sep 30 '13 at 8:23
10  
You can replace / with path to directory grep -Ril "text-to-find-here" ~/sites/ or use . for current directory grep -Ril "text-to-find-here" . – Black Jan 28 '16 at 12:19

You can use the below command as you don't want a file name, but you want to search from all the files. Here are I am capturing "TEXT" from all the log files, making sure that the file name is not printed:

# grep -e TEXT *.log | cut -d' ' --complement -s -f1

Using grep with the -e option is quite quick compared to other options as it is for a PATTERN match.

share|improve this answer

The below command will work fine for this approach:

find ./ -name "file_pattern_name"  -exec grep -r "pattern" {} \;
share|improve this answer
    
what is the point of using find and then grep -r? They are meant for the same, so this is redundant. – fedorqui Dec 23 '15 at 17:02
    
ohh!! corrected , Actually find is for running grep on filtered files and not all, thanks – Pradeep Goswami Dec 30 '15 at 15:25
    
still, this does not make any sense, you can filter with find. – fedorqui Dec 3 '16 at 23:00

I came across this solution twice:

find / -type f -exec grep -H 'text-to-find-here' {} \;

(...)

Is this close to the proper way to do it?

Short answer: Yes, it is very close.


Long answer: This command is correct.

Using just grep -r (grep --recursive) is more straightforward:

grep 'text-to-find-here' -r <path_to_search>

However, your command (combining find and grep) comes in handy sometimes, for example on systems where the grep command doesn't support -r (--recursive), so let's examine the rest of the question:

find / -type f -exec grep -H 'text-to-find-here' {} \;

(...)

However, it doesn't work. It seems to display every single file in the system.

You probably get error messages such as

grep: '<name_of_file_you_do_have_access_to>': Permission denied

You can avoid these by adding option -s (or --no-messages) to grep.

But then you still get errors like

find: '<name_of_file_you_do_have_access_to>': Permission denied

To avoid this, you can add 2>/dev/null at the end of your command, to discard all error messages, which gives:

find / -type f -exec grep -sH 'text-to-find-here' {} \; 2>/dev/null

share|improve this answer

Try this

find . -type f -name some_file_name.xml -exec grep -H PUT_YOUR_STRING_HERE {} \;
share|improve this answer
1  
This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review – Sergey Denisov Nov 18 '15 at 20:14
4  
@SergeyDenisov What gives? This is definitely an answer. (Whether it works or not is another matter.) – jpaugh Nov 18 '15 at 23:43
1  
@jpaugh then you should explain it in details. – Sergey Denisov Nov 18 '15 at 23:55
1  
@SergeyDenisov. It gives a suggested course of action that might produce the correct result. Or, even if it does not, it might help someone else. That's what I mean by, "It's an answer." If you want to know how it works, ask the poster. – jpaugh Nov 18 '15 at 23:58
2  
@jpaugh I'm sure that one line command/code is not enough for a complete answer. You could write a comment giving a suggested course of action, but an answer should include an explanation. That's why this answer was flagged as "Low Quality Post" (not by me). – Sergey Denisov Nov 19 '15 at 9:47

If your grep doesn't support recursive search, you can combine find with xargs:

find / -type f | xargs grep 'text-to-find-here'

I find this easier to remember than the format for find -exec.

This will output the filename and the content of the matched line, e.g.

/home/rob/file:text-to-find-here

Optional flags you may want to add to grep:

  • -i - case insensitive search
  • -l - only output the filename where the match was found
  • -h - only output the line which matched (not the filename)
share|improve this answer
2  
This is equivalent to grep 'text-to-find-here' without file name if find does not find anything. This will hang and wait for user input! Add --no-run-if-empty as an option to xargs. – hagello Jan 28 '16 at 5:46
2  
This combination of find and xargs does not work as intended if file or directory names contain spaces (characters that xargs interprets as separators). Use find … -exec grep … +. If you insist on using find together with xargs, use -print0 and -0. – hagello Jan 28 '16 at 5:50

Try:

find / -type f -exec grep -H 'text-to-find-here' {} \;

which will search all file systems, because / is the root folder.

For home folder use:

find ~/ -type f -exec grep -H 'text-to-find-here' {} \;

For current folder use:

find ./ -type f -exec grep -H 'text-to-find-here' {} \;
share|improve this answer
    
Perhaps the details on differences of folders are obvious to many ...but also very helpful for newbies. +1 – nilon Oct 17 '16 at 18:07
    
what is this adding to the existing answers? – fedorqui Dec 2 '16 at 13:16

protected by durron597 Aug 6 '15 at 19:34

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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