1

I'm trying to find all c files in /usr and its subdirectories that contain "main" but I cant figure out how to make it start searching from the root. I am assuming that the current directory is not in or is usr. So i tried grep -r "main" /usr/*.c Any suggestions? Thanks.

3 Answers 3

2
find /usr -name "*.c" -exec grep -l main {} \;

Is the simple minded version that individually greps each .c file in /usr and outputs it's name.

You could improve it by using xargs to reduce the calls to grep:

find /usr -name "*.c" | xargs grep -l main
2
  • You can also do find ... -exec grep -l main () +. Using + instead of \; tells find to run the command with multiple filenames, similar to the way xargs works.
    – Barmar
    Oct 4, 2012 at 0:44
  • Nice: didn't know that trick!
    – John3136
    Oct 4, 2012 at 0:58
0
WHERETOLOOK=/
find $WHERETOLOOK -type f -iname "*.c" | xargs grep main

EXAMPLES:

$ find / -type f -iname "*.txt" 2> /dev/null | xargs grep INST | head -n 3
grep: /opt/android-sdk/SDK/opt/sun-jdk-1.6.0.33/db/demo/programs/vtis/data/svn_log.txt:Adding message for DATA_SQLDATA_READ_INSTANTIATION_EXCEPTION.
/opt/sun-jdk-1.6.0.33/db/demo/programs/vtis/data/svn_log.txt:        - When a log record is encountered, set newFileStart to INVALID_LOG_INSTANT.
/opt/android-sdk/platforms/android-10/images/NOTICE.txt:DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA

$ find /usr/share/ -type f -iname "*.txt" | xargs grep INST | head -n 3
/usr/share/games/holotz-castle/game/menu/sv/menu.txt:INSTÄLLNINGAR
/usr/share/webapps/phpmyadmin/3.5.2.2/postinst-en.txt:   mkdir ${MY_INSTALLDIR}/config
/usr/share/webapps/phpmyadmin/3.5.2.2/postinst-en.txt:   chown ${VHOST_SERVER_UID}:${VHOST_SERVER_UID} ${MY_INSTALLDIR}/config
xargs: grep: terminated by signal 13
0

If you installed ack (known as ack-grep in Debian/Ubuntu), you could simply run ack -l --cc main from /usr and you'd get your result.

Not the answer you're looking for? Browse other questions tagged or ask your own question.