HOWTO: Searching for a text pattern in all files under a folder
Posted : May 1, 2004 at 10:26 pm [America/Los_Angeles]
As someone who prefers spending more time firing commands on a bash shell prompt than interacting with pretty GUIs via a mouse, I too rely on ‘aliases’ to make myself productive. The following alias is one of my favorites that I religiously setup everytime I get a Unix account:
alias wgrep=’find . -type f -print|xargs grep -i $1′
So, if I want to search for a certain pattern in all files under the current folder, I just type:
(bash-prompt)>wgrep test
Notice that the alias only supports searching for a pattern in the current folder. How would you change the alias to support something like:
(bash-prompt)>wgrep <folder-name> <pattern-name>
- Anand
Category: How do I? |
7 Comments »
No need to use find: “grep -r” recurses through directories already.
Combine it with “-H”, and grep will print filenames along with each match.
Posted by: Charles Miller at May 2, 2004 @ 2:21 am
find . -name “*.java” -exec grep “test” “;” -print
This is from a MS-DOS command line, the escape rules are a bit different in UNIX. If memory serves, something like :
find . -name ‘*.java’ -exec grep test \; -print
–
Cedric
http://beust.com/weblog
Posted by: Cedric at May 2, 2004 @ 8:12 am
Cool. I just tested it and it works great. Thanks Charles.
Posted by: Anand Sharma at May 2, 2004 @ 8:15 am
Thanks for the MS-DOS version as well Cedric. I will test it out and update my post, if possible.
Posted by: Anand Sharma at May 2, 2004 @ 8:18 am
Oops, forgot the {}:
Windows:
find . -name “*.java” -exec grep “test” “{}” “;” -print
UNIX:
find . -name ‘*.java’ -exec grep test {} \; -print
Posted by: Cedric at May 2, 2004 @ 9:08 am
I find find -exec grep can get a bit slow compared to grep -R, because of all the processes started (just as well most versions of grep aren’t using Sun’s JRE). So that got me thinking why not use:
grep myPublicStaticVar $(find . -name “*.java”)
-print is implicit for the local GNU implementation of find. No idea about the compatibility of $() vs “. Windows users will have fun with their command line limit, presumably (is that still in place?).
Posted by: Tom Hawtin at May 3, 2004 @ 4:22 pm
Can’t say I know much about the $() syntax. Will have to check this one out. Thx Tom.
Posted by: Anand Sharma at May 3, 2004 @ 6:41 pm
Leave a Comment