What would be the easiest way to remove all but one word from the end of each line in Vim?
Today, I found a challenge on vimgolf and thought it might be interesting to share my solutions.
Here is the original file
abcd 1 erfg 7721231
Here is the desired result:
The challenge is quite straightforward, delete all but the last characters in the file. I found several ways to tackle this challenge, so let me show you all:
Record a macro, and play it back, so the keystrokes would be
qa $bd0j q 4@a <cr>
It’s quite obvious that all we want to keep from the original files are the numbers. So the regex would be simple to come up with, like something as simple as
/\d\+$<cr> will do. Once you type this into vim, all the numbers at the end of the line will be highlighted. Next you can do:
:%norm dn <cr>
This is the fastest way I can come up with, still, not as fast as the top answers on Vimgolf but it is decent in my opinion. Being slightly different from the option above, it is still using
%norm $bd0 <cr>
normis a quite powerful, and can be used to achieve complex stuff that can be otherwise achieved through a macro.
dthe delete command is useful in many unexpected ways, besides
d0command mentioned above which deletes to the next match and deletes to the beginning of the line respectively. An additional useful variation of
4/xmeaning 4th occurrence of x.