How to delete the last word from each line in vim?
Solution 1
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.
Solution 2
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.)
Solution 3
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
.
Solution 4
To remove the second word from the start of a line, use the following:
:%s/^\(\s*\w\+\s\+\)\w\+\s*/\1/
Update
To treat special characters as part of the word, you have to use the \S
(which matches all non-whitespace characters) instead of \w
(which matches only word characters [0-9A-Za-z_]). Then, the command would be:
:%s/^\(\s*\S\+\s\+\)\S\+\s*/\1/
imbichie
Updated on July 21, 2022Comments
-
imbichie almost 2 years
Please let me know, How I can remove the last word from each line using vim commands? Before :
abcdef 123 xyz 1256 qwert 2 asdf 159
after :
abcdef xyz qwert asdf
Similarly please let me know how to remove the second word from each line using vim command?