My recent favorite vim trick is g + norm. Look in
:h g and
:h norm to see what these do. Basically
g will search all lines in a file for some pattern, and then do something on those lines.
norm will take a string of text as an argument and process that string as though you were pressing the keys in vim yourself, starting in Normal mode.
Combined, you can do some neat things. For example to search for all lines that start with a number, and then add a semi-colon to the end of just those lines:
Note that you need to use
o, or some other way of getting into Insert mode if you want to add text.
One of my favorites (I think I read this on some other site one day) is to find every line containing some text and move those lines to the end of the text file. Sort of an ad-hoc partial way of sorting a file:
:g/some text/norm ddGp
All the vim movement commands work too, so to find every line that has a
", move to the end of the line, move 3 characters back to the left and add a
You can move between lines or add lines to the file too, which makes things interesting. What if you start with this text file:
1 2 3 4 5
And you do this:
Happily this does not blow up into infinite recursion, because vim always makes two passes through the file (one to mark the lines to operate on; a second to actually operate on them); you end up with
1 999 2 999 3 999 4 999 5 999
Vim has a really harsh learning curve. I don't think I discovered
:g at all for a year, and didn't discover
norm for a while after that. Vim will pay off a lot if you stick with it long-term.
This is amazingly powerful and short :g/20/d
It simply says find any line with a 20 in it and run the ex command to delete the line. It has a sick counterpart in :v/20/d (think if it a grep -v) which runs the ex command to delete any line that does not have a 20 in it. This maps basically to your g + norm as :g/20/norm dd
I am trying to find all of the ex commands but there is so much web noise that finding a good basic ex reference is difficult.
:h ex-cmd-index or look here online.
and it pulls all lines matching into one Register...
Copy and move can be done with ex commands