Practice With Vim (I)
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
1 | abcd 1 erfg 7721231 |
Here is the desired result:
1 | 7721231 |
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:
Take 1: Use macro only
Record a macro, and play it back, so the keystrokes would be
1 | qa $bd0j q [email protected] <cr> |
Take 2: Use regex and %norm
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:
1 | :%norm dn <cr> |
Take 3: No regex pure %norm
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
though:
1 | %norm $bd0 <cr> |
Takeaways:
norm
is a quite powerful, and can be used to achieve complex stuff that can be otherwise achieved through a macro.d
the delete command is useful in many unexpected ways, besidesdn
andd0
command mentioned above which deletes to the next match and deletes to the beginning of the line respectively. An additional useful variation ofd
command isd4/x
where4/x
meaning 4th occurrence of x.