How to delete the last word from each line in vim?

Use the following regex (in ex mode):

%s/\s*\w\+\s*$//

This tells it to find optional whitespace, followed by one or more word characters, followed by optional whitespace, followed by end of line—then replace it with nothing.


The question's been answered already, but here's what I'd more likely end up doing:

Record a macro:
qq to record a macro into register "q"
$ to go to the end of the line
daw to delete a word
q to stop recording

Then select the rest of the lines:
j to go down a line
vG to select to the end of the file

And apply the macro:
:norm @q


Some similar alternatives:

:%norm $daw

qq$dawjq (note the added j) then 999@q to replay the macro many times. (Macro execution stops at the first "error" -- in this case, you'd probably hit the bottom of the file, j would not work, and the macro would stop.)


The key for this is the :substitute command; it is very powerful (and often used in vi / Vim).

You need to come up with a regular expression pattern that matches what you want to delete. For the last word, that's whitespace (\s), one or more times \+ (or any number (*), depending on how you want to treat single-word lines), followed by word characters (\w\+), anchored to the end of the line ($). Note that word has a special meaning in Vim; you may want to use a different atom (e.g. \S). Voila:

:%s/\s\+\w\+$//

For the second word, you can make use of the special \zs and \ze atoms that assert for matches, but do not actually match: Anchored at the start (^), match a word, then start the match for a second one:

:%s/^\w\+\s\+\zs\w\+\s\+//

Soon, you'll also want to reorder things, not just remove them. For that, you need to know capturing groups: \(...\). The text matched by those can then be referred to in the replacement part. For example, to swap the first and second words:

:%s/^\(\w\+\s\+\)\(\w\+\s\+\)/\2\1/

For details, have a look at the help, especially :help :substitute and :help pattern.

Tags:

Vim