Basically I want a command that can do the following:

find /path/dir -type f -print0 | xargs -0 grep -l "foo"

Is there an emacs command to do this? If not, then is there a convenient keybinding that I can make? I tried to do the following:

(global-set-key (kbd "C-f") 'find)
(defun find (dir string)
  (insert "find")
  (insert dir)
  (insert "-type f -print0 | xargs -0 grep -l")
  (insert string)

But it doesn't seem to work. It gives me "wrong type argument: commandp, find".


The following does that and presents the results as a dired buffer:

M-x find-grep-dired

You'll also want to know about:

M-x rgrep

(which doesn't support the -l option to grep, but is usually what I want from a recursive regexp search.)


@phils answered the question. This is just to say that the version of find-grep-dired in library find-dired+.el provides a bit more than the vanilla version:

  • It has two optional args, DEPTH-LIMITS and EXCLUDED-PATHS.
  • The interactive spec uses read-from-minibuffer, read-file-name, dired-regexp-history and find-diredp-default-fn.

find-grep-dired is an interactive compiled Lisp function in find-dired+.el.

(find-grep-dired DIR REGEXP &optional DEPTH-LIMITS EXCLUDED-PATHS)

Use Dired on the list of files in DIR whose contents match REGEXP.

The find’ command run (after changing into DIR) is essentially this, where LS-SWITCHES is (car find-ls-option):

find . \( -type f -exec grep grep-program find-grep-options -e REGEXP {} \; \) LS-SWITCHES

Thus REGEXP can also contain additional grep options.

Optional arg DEPTH-LIMITS is a list (MIN-DEPTH MAX-DEPTH) of the minimum and maximum depths. If nil, search directory tree under DIR.

Optional arg EXCLUDED-PATHS is a list of strings that match paths to exclude from the search. If nil, search all directories.

When both optional args are non-nil, the find command run is this:

find . -mindepth MIN-DEPTH -maxdepth MAX-DEPTH \( -path EXCLUDE1 -o -path EXCLUDE2 ... \)
       -prune -o -exec grep-program find-grep-options -e REGEXP {} \; LS-SWITCHES

where EXCLUDE1, EXCLUDE2... are the EXCLUDED-PATHS, but shell-quoted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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