7

How can I find and delete lines which start with the text in?

I use the command C-M-s ^in to find all lines starting with in, but then I don't really know what to do.

Drew
  • 29,895
  • 7
  • 74
  • 104

2 Answers2

11

M-x flush-lines RET ^in RET

C-h f flush-lines tells you:

flush-lines is an interactive compiled Lisp function in replace.el.

It is bound to menu-bar edit flush-lines.

(flush-lines REGEXP &optional RSTART REND INTERACTIVE)

Delete lines containing matches for REGEXP.

When called from Lisp (and usually when called interactively as well, see below), applies to the part of the buffer after point. The line point is in is deleted if and only if it contains a match for regexp starting after point.

If REGEXP contains upper case characters (excluding those preceded by \) and search-upper-case is non-nil, the matching is case-sensitive.

Second and third arg RSTART and REND specify the region to operate on. Lines partially contained in this region are deleted if and only if they contain a match entirely contained in it.

Interactively, in Transient Mark mode when the mark is active, operate on the contents of the region. Otherwise, operate from point to the end of (the accessible portion of) the buffer. When calling this function from Lisp, you can pretend that it was called interactively by passing a non-nil INTERACTIVE argument.

If a match is split across lines, all the lines it lies in are deleted. They are deleted before looking for the next match. Hence, a match starting on the same line at which another match ended is ignored.

Drew
  • 29,895
  • 7
  • 74
  • 104
  • 1
    And for anyone who wasn't aware of either, the `keep-lines` command complements `flush-lines`. They are both very useful. – phils Nov 29 '17 at 23:04
  • 3
    @phils: Yes. And it might help to remember them, or to rediscover them later, by their aliases: `delete-matching-lines` and `delete-non-matching-lines`. – Drew Nov 30 '17 at 00:21
  • Is there anyway to interactively delete matching lines from the whole buffer, without losing your current place? – NetMage Apr 23 '20 at 20:03
  • @NetMage: `C-SPC`, to set a mark at point. Then `M-<` to go to bob. Then flush. Then `C-u C-SPC` to go back where you were. – Drew Apr 23 '20 at 20:24
  • That's annoying :) Surprised all the point/region commands don't take an argument to do the whole buffer. – NetMage Apr 23 '20 at 21:06
  • @NetMage: It is simple to write a command that does what you want. And since you ask to do it "interactively", even without a command you can do that with `M-: (flush-lines REGEXP nil (buffer-size) t)`, where `REGEXP` is the regexp you want to match. – Drew Apr 23 '20 at 22:31
2

query-replace-regexp "in.*" to "" will be work. you should not input " to the prompt

carlos
  • 346
  • 1
  • 10