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?

  • 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? Commented Feb 1, 2019 at 10:53
  • 1
    Considering that you manually provide arguments to grep, it doesn't really matter.
    – user12563
    Commented Feb 1, 2019 at 15:19

3 Answers 3


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).


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/*[^~]

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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