3

M-x grep can be used to find strings in files. But I'm not interested in backup files (those whose name ends with a ~).

How should I ignore those files when using the grep command?

DataHungry
  • 247
  • 1
  • 7
  • Is this a question about how to use grep (if you do `C-h i` and navigate to coreutils then grep it should help) or how to use `M-x grep` in emacs? – Dan Robertson Feb 01 '19 at 10:53
  • 1
    Considering that you manually provide arguments to `grep`, it doesn't really matter. –  Feb 01 '19 at 15:19

3 Answers3

7

Emacs provide lgrep and rgrep as convenient interfaces for grep. These commands may invoke grep on the command line with grep options systematically (see also the GNU Emacs Reference Manual). More specifically, the user option grep-find-ignored-files (discovered after searching in the source code and in the integrated documentation) may be set to ignore some files.

M-x customize-variable
Customize variable: grep-find-ignored-files

However, the variable grep-find-ignored-files already contains the value *~ in my default setting so lgrep and rgrep ignore backup files.

In my GNU environment, the variable allows to add several --exclude= options on the command line to grep when a user invokes lgrep dynamically.

Note: The user may modify the settings globally by customizing the group grep (customize-group).

1

You can modify the pattern match to exclude file with names ending in ~ via [^~]. When M-x grep prompts you for the grep command, use something like:

grep match-text ./path/*[^~]
Tyler
  • 21,719
  • 1
  • 52
  • 92
1

You could put your backup files somewhere else. When you do a grep emacs will ask for the root directory for the search, defaulting to the current directory. You could specify a directory for the backup files that is outside the places you usually search. You can do this by setting backup-directory-alist.

(setq backup-directory-alist `(("." . "~/.saves")))

Full details are here: How do I control how Emacs makes backup files?

Iain
  • 194
  • 10