3

How can I use find to find files without the preceding directory (./) in a way that also works with -exec?

My goal is to grep through an Apache log to see if any of the files have been accessed recently. This is what I have so far:

find . -max-depth 1 -type d \
  -exec grep \"GET /{}\" /var/log/apache2/blah.com \;

I found a solution using -printf "%f\n", but that does not work with -exec.

1
  • It should be -maxdepth, not -max-depth
    – Lenik
    Nov 19, 2010 at 1:13

3 Answers 3

2
find . -maxdepth 1 -type d -printf "%f\0" | \
     xargs -0 -I {} grep 'GET /{}' /var/log/apache2/blah.com
2

Try:

grep -Ff <(find . -maxdepth 1 -type d | sed -e 's,^\.,GET ,') /var/log/apache2/blah.com

Or, if you want to substitute {} within find command:

find . -maxdepth 1 -type d -exec bash -c 'F={}; F=${F#./}; grep -F "GET /$F" /var/log/apache2/blah.com' \;
0

Since you're not doing a recursive search, there's no need to use find, unless you wanted to include only directories and not symbolic links to directories. Assuming there are no directories whose name begins with a dot (if there are, use for x in .*/ */; do …), the following will search the names of all directories and symbolic links to directories in the current directory:

for x in */; do grep -F "GET /${x%/}" /var/log/apache2/blah.com; done

If you were doing a recursive search, you could avoid a leading dot by searching from * rather than . (same remark as above regarding names beginning with a dot).

find * -type d -exec grep -F "GET /${x%/}" /var/log/apache2/blah.com

Another possibility is to postprocess the output of find. This is especially useful in combination with grep's ability to search multiple newline-separated patterns.

grep -F "$(find . -type d | sed -e 's!^\.!GET !')" /var/log/apache2/blah.com

Note that in all cases you're assuming there aren't any characters in the directory names that would be escaped in the Apache log. This is solvable with a little further postprocessing of the find output.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .