Vim: g + norm
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:
:g/^\d/norm A;
Note that you need to use i, A, 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 ~:
:g/"/norm $hhhi~
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:
:g/\d/norm o999
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

8 Comments
I really like this tip. I feel so dense that I don't get vim more completely.
Vim has a really harsh learning curve. I don't think I discovered
:gat all for a year, and didn't discovernormfor 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.
Try
:h ex-cmd-indexor look here online.I think this is the best vim tip I have ever read. It easily trumps all the little macros and :s// I write. I am so grateful you shared this with us.
Came across this gem recently
:g/matchstring/y Aand it pulls all lines matching into one Register...
thx.
ver nice info.
Copy and move can be done with ex commands
candm:copy to end of file
move to end of file
Speak your Mind
Preview