2

I have a regular expression that can match several lines of text, and I want to use it to search every file in a directory. The problem is that standard regrep command works line by line, so this multiline regular expression won't work.

Is there any alternative Lisp function/command that can do what I want?

2 Answers2

5

Elgrep works with Emacs regular expressions. Newlines within the regular expression can be input by the key sequence C-q C-j. The input of newlines works equally well when you use elgrep-menu (menu item Tools -> Search Files (Elgrep)...) or when you call elgrep directly (e.g., via M-x elgrep RET).

You can install elgrep via Melpa.

Tobias
  • 32,569
  • 1
  • 34
  • 75
2

n.b. The following isn't really useful beyond a simple list of matching filenames as the reported matching line will almost certainly be the first line -- so Emacs can't trivially take you to the matching text.


GNU grep supports the (non-POSIX) command line option -z (or --null-data), with the effect:

Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline

So you can (most likely) match against your entire file with that, with some caveats:

  • Output is also NUL-terminated, so you need to parse that.
  • NUL bytes are already used in the normal output (when grep-use-null-filename-separator is enabled), so you may need to differentiate those.
  • You likely don't want to see the full text of the matching file in the output.

The following will probably do the trick for post-processing the NUL chars.

perl -pe 's/\0(?![0-9]+:)/\n/g'

And the --only-matching option will restrict the amount of displayed output.

Example using M-x grep:

grep --only-matching --null-data --color -nH --null -e REGEXP FILES | perl -pe 's/\0(?![0-9]+:)/\n/g'
phils
  • 48,657
  • 3
  • 76
  • 115