Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Emacs, How to replace only on matching lines

Tags:

emacs

elisp

For example: In VIM,

test
sample replace
test1
replace
sample test2

:g/sample/s/replace/test3/ - will replace "replace" only on matching lines with "sample"

test
sample test3
test1
replace
sample test2

In VIM, to replace only on non-matching lines can be done by :v/sample/s/replace/test3 - will replace "replace" only on non-matching lines which does not contain "sample"

test
sample replace
test1
test3
sample test2

How can above thing can be accomplished using emacs?

like image 729
rajashekar Avatar asked Dec 02 '22 01:12

rajashekar


1 Answers

Are you using Emacs 24 perchance? If so, you can use the built-in occur-edit-mode:

  • First use one of the occur functions to obtain a buffer of lines matching your pattern:
    M-x occur RET (pattern) RET
  • Now press e to enter occur-edit-mode to perform interactive edits on those lines only.
  • Search and replace.
  • Finally, C-cC-c to exit occur-edit-mode, and q to dismiss the occur buffer.

There are third-party libraries to perform similar tricks on earlier versions of Emacs. I believe moccur-edit is one of them, but I've never used it.

edit: Regarding the second part of your question, while I'm not familiar with a more direct way of accomplishing that, we can hack this same method to achieve it:

  • M-x occur RET . RET to obtain occur buffer containing all lines
  • C-xC-q to make occur buffer writable
  • M-x flush-lines RET (pattern) RET to delete matching lines
  • C-xC-q to make occur buffer read-only again
  • e to invoke occur-edit-mode (and then continue as before...)
like image 126
phils Avatar answered Dec 06 '22 22:12

phils