How to grep all the sub folders on Linux

I need to find something say, function_name() string in sub folders and directories on Linux. What Linux command I need to type? Is it find or grep? Also how would I look for function_name() and function_NAME() too (Case -insensitive search using grep )?

Try using the -r or --recursive and -i or --ignore-case with your grep.

Grep all the sub folders on Linux command-line

grep -r -i 'function_to_search()' /path/to/dir/

List only file names but do not show matched text/functions in ~/projects/ directory and all sub-dirs

grep -l -r -i 'foo()' ~/projects/

Prefix (add) each line of output with the 1-based line number within its input file

grep -n -H -r -i 'foo()' ~/projects/

grep options

  • -i : Ignore case distinctions in both the PATTERN and the input files. Match foo, FOO, Foo etc.
  • -r : Read all files under each directory, recursively, following symbolic links only if they are on the command line.
  • -l : Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.
  • -H : Print the file name for each match. This is the default when there is more than one file to search.
  • -n : Show line numbers

Make sure you use the egrep instead of grep when you need an extended regular expression (ERE):

egrep -i -r 'ERE_HERE' /path/to/search/
egrep -i -r 'main|foo|bar' ~/projects/

Perfecto, this is what i needed :pray:

question: what about Linux find command? can i pass grep to find? which one will be faster for searching 1000s of code files on the Linux server?

Yes, we can use find and grep as follows to search for all Python files (*.py):

find ~/projects/ -name '*.py' -exec grep -H "function_name_to_search" {} \;

Here is equivalent grep command:

grep  -i -r --include "*.py" "function_name_to_search" /path/to/dir

Here is how I would search the entier file system for *.c files and main():

find / -type f -print0 | LC_ALL=C xargs -r0 -P2 grep -Hi 'main()'

Try passing above commands with time and strace and see which one is faster. For example:

strace -cf grep  -i -r --include "*.py" "function_name_to_search" /path/to/dir
strace -cf find / -type f -print0 | LC_ALL=C xargs -r0 -P2 grep -Hi 'main()'

Run programs and summarize system resource usage

time grep  -i -r --include "*.py" "function_name_to_search" /path/to/dir
time -cf find / -type f -print0 | LC_ALL=C xargs -r0 -P2 grep -Hi 'main()'
1 Like

Take a look at ag:

1 Like

Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki