This morning, I was looking for a way to delete a line and confirm the deletion at the same time. I'm familiar with this command:
:g/pattern/d
In the above command, all lines containing the text pattern (regular expression) are deleted. However, that's not what I wanted. I wanted to be able to make changes similar to the search and substitution command which allows you to confirm substitutions like this:
:g/search pattern/subtitution pattern/gc
I then came across this web page:
Much better! From this web page I was able to figure out that the following command will confirm all deletions of lines containing the word banana:
:g/banana/s/^.*$\n//c
Here are the working parts of the above command:
- The colon gets you into ex commands, a set of commands that are line-oriented.
- The g prefix addresses each and ever line in your file. The g prefix is global, in other words.
- The first set of slashes that contain banana is the search pattern. This identifies lines that are to be addressed, which really means lines that are to be acted upon.
- The s command is the substitution command. Typically, the substitution command has s/// as its most basic syntax.
- The basic idea of the substitution command is that you clobber something with something else. You can literally clobber something with something else by typing s/something/something else/.
- In the example command above, ^.*$\n is being clobbered by absolutely nothing. In other words, ^.*$\n is being deleted in its entirety.
- The pattern ^.*$\n means the whole line plus the newline at the end of the line. To understand better, read about regular expressions. Regular expressions are a whole topic on to themselves.
- The final part of the command is the confirmation suffix which is represented by lowercase c. A simple y or n is used to confirm yes or no. No means the line in the file will not be deleted.
As is so often the case in vim, it is the combination of commands that lends vim its power.
Ed Abbott