0

I'd like to write an elisp function that allows me to replace any line in my buffer matching a regex pattern <PATTERN> with text <TEXT>. In other words, if line N matches <PATTERN>, then line N is replaced with <TEXT>.

For example, if <PATTERN> is ^foo and <TEXT> is bar, then running the elisp function within the buffer

Arcu ante habitasse inceptos congue.
Odio magnis at aenean at est.
foo eget, eu vitae.
Class.
Adipiscing dis donec tellus imperdiet curae.
fooSem sit tristique lacus ut porta accumsan.
Amet ad duis velit sit amet.

would change the buffer to

Arcu ante habitasse inceptos congue.
Odio magnis at aenean at est.
bar
Class.
Adipiscing dis donec tellus imperdiet curae.
bar
Amet ad duis velit sit amet.

This is exactly the behavior of the sed command sed '/^foo/c\bar'.

1
  • This is nothing more complicated than a regexp replacement with .* suffixed to your regexp. Or ^.*foo.* for matching anywhere in a line. Of course you can write a function which searches for only the original pattern and then manipulates the current line each time it finds a match, but my point is that you don't need to do that unless you really want to.
    – phils
    Jul 29, 2022 at 2:44

1 Answer 1

1

Is it possible to…

The answer to this type of question is always yes.

In your case, just run (replace-regexp "^foo.*$" "bar"). You can do this interactively with query-replace-regexp, which prompts you to verify each match. This helps prevents mistakes. It is bound to C-M-% by default.

Your Answer

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

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