I'd like to use Ex mode
:g/pattern/d to delete most (but not all) of the rows containing
pattern, but I want to see each one first and confirm before deleting, similar to
:s/pattern/foo/gc. Is there a way to do this, in Ex mode or otherwise?
One way to achieve what you want to do is to use the
:s command inside your
We know that we can delete a line, with a confirmation using the following substitution:
This will replace all the characters (
.*) and the next end of line character (
\n) with nothing, effectively deleting the line. The
c flag at the end of the substitution prompts for a confirmation.
:h :g tells us that the command
:g takes a pattern and a command. The pattern is up to you to choose but the command can be the one we used before, making your
:g command like this:
pattern by your own pattern and you are good to go.
EDIT As Luc pointed out in the comments, this solution has some flaws: If you have consecutive lines matching the pattern only the first one will be handled.
A solution could be to use
:g/pattern/s/.*\|.*\n//c but this will leave empty lines instead of deleting them completely. These remaining lines could be handled with
:g/^$/d but that require to have no other empty lines in the buffer.
If you have empty lines in the buffer, you could replace the lines to be deleted with a marker
:g/pattern/s/.*\|.*\n/deleteme/c and then delete the lines containing this marker with
Sometimes ago, on SO, I've posted a solution to have a
:global command which asks for confirmation before executing anything (
:delete in your case): https://stackoverflow.com/a/46830106/15934
It's a little bit convoluted :D. It's shipped with my library plugin, and it can be used with
Note: unlike the
:g/pattern/s/.*\n//c solution, the confirmation is global, and it doesn't skip consecutive lines that shall be removed.
In the end, the only vanilla solution that I'm aware of, and that works in all situations (consecutive lines, first line (see Q/A on SO)) is
:global with confirm, it's
:substitute hijacked to remove entire lines, with confirm.