How can I use grep to find a word inside a folder?
Asked Answered
G

14

703

In Windows, I would have done a search for finding a word inside a folder. Similarly, I want to know if a specific word occurs inside a directory containing many sub-directories and files. My searches for grep syntax shows I must specify the filename, i.e. grep string filename.

Now, I do not know the filename, so what do I do? A friend suggested to do grep -nr string, but I don't know what this means and I got no results with it (there is no response until I issue a Ctrl + C).

Gonzales answered 8/11, 2010 at 6:50 Comment(0)
X
1113
grep -nr 'yourString*' .

The dot at the end searches the current directory. Meaning for each parameter:

-n            Show relative line number in the file
'yourString*' String for search, followed by a wildcard character
-r            Recursively search subdirectories listed
.             Directory for search (current directory)

grep -nr 'MobileAppSer*' . (Would find MobileAppServlet.java or MobileAppServlet.class or MobileAppServlet.txt; 'MobileAppASer*.*' is another way to do the same thing.)

To check more parameters use man grep command.

Xeric answered 17/12, 2012 at 4:58 Comment(6)
What's the business with *? It will either result in shell wildcard expansion (if there are filenames matching the wildcard pattern), or grep will take it as 0-or-more repetition operator for the character preceding *.Grugru
Now let's consider both possibilities for grep -nr MobileAppSer* . 1. Assume we have 3 files in the current directory matching MobileAppSer* wildcard pattern: named MobileAppServlet.java, MobileAppServlet.class, MobileAppServlet.txt. Then grep will be invoked like this: grep -nr MobileAppServlet.class MobileAppServlet.java MobileAppServlet.txt .. It means search for text "MobileAppServlet.class" in files MobileAppServlet.java, MobileAppServlet.txt, and elsewhere in the current directory - which surely isn't what the user wants here.Grugru
2. In case there are no files in the current directory matching the MobileAppSer* wildcard pattern, grep will receive the argument MobileAppSer* as-is and thus will take it as search for text "MobileAppSe" followed by 0 or more occurrences of "r", so it will attempt to find texts "MobileAppSe", "MobileAppSer", "MobileAppSerr", "MobileAppSerrr", etc. in current directory's files contents - not what the user wants either.Grugru
This is a dubious choice of regex. Usta has pointed this out.Rigveda
I ran grep -nr 'yourString*' . and got some files with "binary file matches". You can add --text or -a to prevent this: grep -anr 'yourString*' .Adelleadelpho
I think you want to remove the asterisk: grep -anr 'yourString' .Biform
G
159
grep -nr string my_directory

Additional notes: this satisfies the syntax grep [options] string filename because in Unix-like systems, a directory is a kind of file (there is a term "regular file" to specifically refer to entities that are called just "files" in Windows).

grep -nr string reads the content to search from the standard input, that is why it just waits there for input from you, and stops doing so when you press ^C (it would stop on ^D as well, which is the key combination for end-of-file).

Grugru answered 8/11, 2010 at 6:54 Comment(3)
Hey, so if i want to search for a string irrespective of the case, must I do this: grep -i -nr "my word" .Gonzales
@kiki: Yes, which is equivalent to grep -inr "my word" .Grugru
@kiki: -r for grep means search in subdirectories recursively and -n means prefix each line of output with the corresponding line number of the file which contains that line. man grep describes all of this, and much more.Grugru
D
74

GREP: Global Regular Expression Print/Parser/Processor/Program.
You can use this to search the current directory.
You can specify -R for "recursive", which means the program searches in all subfolders, and their subfolders, and their subfolder's subfolders, etc.

grep -R "your word" .

-n will print the line number, where it matched in the file.
-i will search case-insensitive (capital/non-capital letters).

grep -inR "your regex pattern" .
Deloisedelong answered 8/11, 2010 at 7:14 Comment(2)
./* means all files in the current directory, -R means recursive (searching subdirectories etc.)Deloisedelong
Thanks. And grep -inR "[0-9a-fA-F]{32}" . helps find hashes (which are hex strings) in the files within the current directory. https://mcmap.net/q/21349/-regular-expression-for-a-hexadecimal-numberMet
F
40

There's also:

find directory_name -type f -print0 | xargs -0 grep -li word

but that might be a bit much for a beginner.

find is a general purpose directory walker/lister, -type f means "look for plain files rather than directories and named pipes and what have you", -print0 means "print them on the standard output using null characters as delimiters". The output from find is sent to xargs -0 and that grabs its standard input in chunks (to avoid command line length limitations) using null characters as a record separator (rather than the standard newline) and then applies grep -li word to each set of files. On the grep, -l means "list the files that match" and -i means "case insensitive"; you can usually combine single character options so you'll see -li more often than -l -i.

If you don't use -print0 and -0 then you'll run into problems with file names that contain spaces so using them is a good habit.

Flavorous answered 8/11, 2010 at 7:40 Comment(3)
can I exclude certain directories? @muistooshortCailly
@Ferologics There should be, check man find from the command line to see what options your find supports.Flavorous
"but that might be a bit much for a beginner" -- the length doesn't change depending on your personal experience!Margoriemargot
A
29
grep -nr search_string search_dir

will do a RECURSIVE (meaning the directory and all it's sub-directories) search for the search_string. (as correctly answered by usta).

The reason you were not getting any anwers with your friend's suggestion of:

grep -nr string

is because no directory was specified. If you are in the directory that you want to do the search in, you have to do the following:

grep -nr string .

It is important to include the '.' character, as this tells grep to search THIS directory.

Amie answered 8/11, 2010 at 6:59 Comment(1)
Hi, what do i do, if i have to search 2 words with a space in between? Should the words be specified within quotes? i.e grep -nr "my word" .Gonzales
O
13

Why not do a recursive search to find all instances in sub directories:

grep -r 'text' *

This works like a charm.

Oral answered 6/8, 2013 at 22:2 Comment(1)
No need to quote search string with no special chars like spacesOctangular
V
10

Similar to the answer posted by @eLRuLL, an easier way to specify a search that respects word boundaries is to use the -w option:

grep -wnr "yourString" .
Valenevalenka answered 21/12, 2017 at 17:22 Comment(2)
In the cmd prompt or windows terminal the term grep is not recognizedKistler
@Kistler grep is a Unix command. itechtics.com/using-findstr-windowsSprayberry
S
5

Another option that I like to use:

find folder_name -type f -exec grep your_text  {} \;

-type f returns you only files and not folders

-exec and {} runs the grep on the files that were found in the search (the exact syntax is "-exec command {}").

Scourings answered 3/6, 2013 at 14:46 Comment(0)
F
5
  1. grep -r "yourstring" * Will find "yourstring" in any files and folders

Now if you want to look for two different strings at the same time you can always use option E and add words for the search. example after the break

  1. grep -rE "yourstring|yourotherstring|$" * will search for list locations where yourstring or yourotherstring matches
Fullscale answered 25/11, 2015 at 14:54 Comment(0)
D
5
grep -R "string" /directory/

-R follows also symlinks when -r does not.

Dotty answered 30/1, 2019 at 13:47 Comment(0)
G
4

The answer you selected is fine, and it works, but it isn't the correct way to do it, because:

grep -nr yourString* .

This actually searches the string "yourStrin" and "g" 0 or many times.

So the proper way to do it is:

grep -nr \w*yourString\w* .

This command searches the string with any character before and after on the current folder.

Gall answered 9/5, 2013 at 22:13 Comment(1)
however grep -nr yourString works too, as it looks for the bare yourString anywhere in the line (or at least it does on my system, OSX Lion)Futile
W
2

The following sample looks recursively for your search string in the *.xml and *.js files located somewhere inside the folders path1, path2 and path3.

grep -r --include=*.xml --include=*.js "your search string" path1 path2 path3

So you can search in a subset of the files for many directories, just providing the paths at the end.

Whitver answered 4/5, 2020 at 12:35 Comment(0)
M
1

Run(terminal) the following command inside the directory. It will recursively check inside subdirectories too.

grep -r 'your string goes here' * 
Marcmarcano answered 8/1, 2020 at 5:15 Comment(0)
G
-3

Don't use grep. Download Silver Searcher or ripgrep. They're both outstanding, and way faster than grep or ack with tons of options.

Giuseppinagiustina answered 25/7, 2017 at 2:8 Comment(1)
These maybe great tools but this doesn't answer how I would use these tools to accomplish what the OP is asking.Suffruticose

© 2022 - 2024 — McMap. All rights reserved.