Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to find a string/regex match in files recursively? (UNIX)

I have had to do this several times, usually when trying to find in what files a variable or a function is used.

I remember using xargs with grep in the past to do this, but I am wondering if there are any easier ways.

like image 246
Murat Ayfer Avatar asked Oct 09 '08 05:10

Murat Ayfer


People also ask

How do you search for a string in all files recursively in Linux?

Use grep to search for lines of text that match one or many regular expressions, and outputs only the matching lines. Using the grep command, we can recursively search all files for a string on a Linux.

How do I search for a string in a directory recursively?

To recursively search for a pattern, invoke grep with the -r option (or --recursive ). When this option is used grep will search through all files in the specified directory, skipping the symlinks that are encountered recursively.

How do you find a string in all files in a directory in Unix?

Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.


2 Answers

grep -r REGEX . 

Replace . with whatever directory you want to search from.

like image 92
Chris Jester-Young Avatar answered Sep 23 '22 11:09

Chris Jester-Young


The portable method* of doing this is

find . -type f -print0 | xargs -0 grep pattern 

-print0 tells find to use ASCII nuls as the separator and -0 tells xargs the same thing. If you don't use them you will get errors on files and directories that contain spaces in their names.

* as opposed to grep -r, grep -R, or grep --recursive which only work on some machines.

like image 28
Chas. Owens Avatar answered Sep 23 '22 11:09

Chas. Owens