In Windows, if I wanted to find a string across all files in all subdirectories, I would do something like
findstr /C:"the string" /S *.h
However, in Linux (say, Ubuntu) I have found no other way than some piped command involving find, xargs, and grep (an example is at this page: How can I recursively grep through sub-directories?). However, my question is different: is there any single, built-in command that works through this magic, without having to write my shell script?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
GNU grep allows searching recursively through subdirectories:
grep -r --include='*.h' 'the string' .
Method 2
grep -r searchpattern /path/to/start/in
Where /path/to/start/in/ can be just “.” for the current directory.
Method 3
No. find -name *.h -print0 | xargs -0 grep -l 'the regex' is as magic as it gets.
Method 4
To find string from given directory use below command
find <fullDirectoryPath> -name '*' -exec grep -l '<StringToFind>' {} ;
For example:
find /apps_bev/apps/xfer/export/02210 -name '*' -exec grep -l '38221000001032' {} ;
Method 5
is there any single, built-in command that works through this magic … ?
To be pedantic, no, you cannot assume such a command exists.
There are many different implementations of Unix, and each has its different quirks. POSIX, the common denominator (and closest thing to a standard across Unices) does not specify such an option for grep.
As mentionned in other answers, GNU’s implementation of grep has a non-standard option that does what you want. While this particular implementation might be common on Linux systems, you cannot assume its availability on any Unix, even some Linux systems.
Finally, I should mention that it is the Unix philosophy to favor the combination of several primitive programs, over the use of one big monolithic executable attempting to do everything at once.
In your case, crawling the file system and matching regexp in a stream are two separate tasks. It is only normal to treat each in a separate program.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0