[SWLUG] Any tips on locating this file.

Carter N. N.Carter at swansea.ac.uk
Wed Aug 18 10:34:55 UTC 2004


Hi all,

>What I need is either a way of searching all files for the string. which is

>Perhaps some kind of permuation on the find command?

There are a variety of ways of applying commands, such as grep, to specified
files, including sub-directories. Some are based on the xargs and find
commands.

looking for all mentions of a variable named counter in source code files,
which have names ending in .c ...


Using xargs:

    find ./ -name '*.c' | xargs grep counter

This is equivalent to:

    grep foo `find ./ -name '*.c'`

The following will print the filenames of the files containing foo.

    find ./ -name '*.c' | xargs grep -l foo


Using find's -exec option...

    find ./ -name '*.c' -exec grep foo {} \;

The -exec method tends to be slower because grep is executed once per file
found. If the command to be executed (in this case grep) can take multiple
files as an argument, the xargs and reverse-quotes methods are faster. This
is because grep is executed only once (with the concatenation of the files
found) instead of many times. This is especially true when recursing into a
big directory structure.

The advantage of the exec method is that if it returns 0 (found) then any
subsequent arguments are also evaluated. To print the names of matched
files:

    find ./ -name '*.c' -exec grep foo {} \; -print 


Hope this helps.

Neil
--------------------------------------------
Neil Carter            Psychology Department
IT Technician    University of Wales Swansea
                       Wales, United Kingdom

http://psy.swansea.ac.uk/staff/Carter/





More information about the Swlug mailing list