Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs, removing all lines that don't match?

Tags:

regex

emacs

I use the (query-replace-regexp "from" "to") expression regularly when making large changes in a text file.

I'd like a regular expression, if one exists, for removing all lines that don't match. For example, in a RedHat SPEC file for building a RPM I want to leave just the lines that begin with /^Patch/ in them (and delete all non-matching lines). Easy enough with grep -E '^Patch' but is there a way in Emacs?

I tried:

(query-replace-regexp "^\\(?!Patch\\)[^\r\n]*$" "")

to no avail (negative-lookahead appears unsupported).

Any ideas?

like image 749
PP. Avatar asked Nov 18 '10 12:11

PP.


3 Answers

Try M-x keep-lines ^Patch instead:

(keep-lines REGEXP &optional RSTART REND INTERACTIVE)

Delete all lines except those containing matches for REGEXP.

There is also the opposite command, M-x flush-lines, which removes lines matching a regexp.

like image 94
Gareth Rees Avatar answered Nov 18 '22 16:11

Gareth Rees


use M-x delete-non-matching-lines and M-x delete-matching-lines

like image 42
Benny Mohr Avatar answered Nov 18 '22 16:11

Benny Mohr


If it's just "Patch" you are looking for, you can identify lines not matching ^Patch by using

^([^P]|P[^a]|Pa[^t]|Pat[^c]|Patc[^h])[^\r\n]*$

I admit, it is rather ugly, though. =)

like image 5
Jens Avatar answered Nov 18 '22 15:11

Jens