Thursday, 27 January 2011

Finding text within files recursively

Occasionally, I need to search for text strings within files within directories on a UNIX / Linux command line. I find that the following is able to assist me in finding the correct line:

find . -exec grep -i search_string {} /dev/null \;

Here is an example of it in action:

[ ric_man @ mymachine ~/test ] 521 $ ls -alR
.:
total 11K
drwxr-xr-x+ 1 ric_man None 0 2011-01-27 10:12 ./
drwxr-xr-x+ 1 ric_man None 0 2011-01-27 10:09 ../
-rwx------+ 1 ric_man None 1.2K 2011-01-17 15:03 OBS_bulk.txt*
-rwxr-xr-x 1 ric_man None 291 2011-01-17 15:41 convert.sh*
drwxr-xr-x+ 1 ric_man None 0 2011-01-27 10:11 dir1/
drwxr-xr-x+ 1 ric_man None 0 2011-01-27 10:12 dir2/
-rw-r--r-- 1 ric_man None 10 2011-01-27 10:12 fileA.txt
-rw-r--r-- 1 ric_man None 83 2010-12-23 13:55 input.txt
-rwxr-xr-x 1 ric_man None 1.1K 2010-12-23 14:03 runme.sh*

./dir1:
total 2.0K
drwxr-xr-x+ 1 ric_man None 0 2011-01-27 10:11 ./
drwxr-xr-x+ 1 ric_man None 0 2011-01-27 10:12 ../
-rw-r--r-- 1 ric_man None 39 2011-01-27 10:11 file1.txt
-rw-r--r-- 1 ric_man None 39 2011-01-27 10:11 file2.txt

./dir2:
total 1.0K
drwxr-xr-x+ 1 ric_man None 0 2011-01-27 10:12 ./
drwxr-xr-x+ 1 ric_man None 0 2011-01-27 10:12 ../
-rw-r--r-- 1 ric_man None 18 2011-01-27 10:12 fred.conf
[ ric_man @ mymachine ~/test ] 522 $ find . -exec grep -i snack {} /dev/null \;
./dir1/file1.txt:Here is the string to be found - snack
./dir1/file2.txt:Here is the string to be found - snack
./dir2/fred.conf:Snack found here!
./fileA.txt:Snack me!

In Microsoft Windows environments, I think there's a search facility, but it is slow, and sometimes inaccurate.

No comments:

Post a Comment