7

I hope it's a simple problem..

I'd like to search for the regexp 'thisWord' only in the marked files of a dired buffer.

Usually I used in the dired buffer:

  1. M-x grep and then in the mini-buffer
  2. grep -r -nH 'thisWord' .

But this searches all the files of the directory not just the marked ones.

Well, the dired mode of emacs has the possibility to restrict the search on the marked files with just using A (dired-do-find-regexp). But the results are listed in the unusual "xref format", I need the "grep format":

./file-a.org:16253: ..thisWord...

I there a simple way to get the search results of the marked files in the "grep format"?

rl1
  • 346
  • 1
  • 16

3 Answers3

6

If you use library Dired+ (dired+.el) then you can use command dired-do-grep (bound by default to M-g in Dired mode) to do what you request.

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

(diredp-do-grep COMMAND-ARGS)

Run grep on marked (or next prefix arg) files.

A prefix argument behaves according to the ARG argument of dired-get-marked-files. In particular, C-u C-u operates on all files in the Dired buffer.

Drew
  • 75,699
  • 9
  • 109
  • 225
  • Thanks! I couldn't test it. I install new packages only if it is necessary. – rl1 Feb 19 '17 at 19:11
  • @user52408: Probably best to mention in the text of your question if you're unwilling to use code which isn't part of Emacs. – phils Feb 20 '17 at 10:09
  • @phils Oh, there is a misunderstanding. I'm not unwilling, but it prefer solutions "within emacs". I can mention this next time. – rl1 Feb 20 '17 at 14:29
4
(defun dired-grep-marked-files ()
"`i` case insensitive; `n` print line number;
`I` ignore binary files; `E` extended regular expressions."
(interactive)
  (let* ((files (dired-get-marked-files))
         (search-term (read-string "regex:  "))
         (grep-command
           (concat
             grep-program
             " "
             "-inIE --color=always -C2"
             " "
             search-term
             " "
             (mapconcat 'identity files " "))))
    (when (and files search-term grep-command)
      (compilation-start grep-command 'grep-mode (lambda (mode) "*grep*") nil))))
lawlist
  • 18,826
  • 5
  • 37
  • 118
3

Eshell's grep is compatible with grep(1) and uses Emacs's internal grep interface, thus you can try something like the following:

M-x dired-do-eshell-command RET grep -nH --color your-search--pattern RET
(defun dired-do-eshell-command (command)
  "Run an Eshell command on the marked files."
  (interactive "sEshell command: ")
  (let ((files (dired-get-marked-files t)))
    (eshell-command
     (format "%s %s" command (mapconcat #'identity files " ")))))
xuchunyang
  • 14,302
  • 1
  • 18
  • 39