How to delete everything after every a specified word in vim
so i have this string
fruit banana
fruit apple
fruit grape
planet jupiter
planet mars
planet saturn
And I want to change those string to like this
fruit
fruit
fruit
planet jupiter
planet mars
planet saturn
The question is, how can I do this with a vim?
At least 5 ways to do it:
With a substitution
With substitutions you can do many things (see :help substitute
). One is that
you can remember the first word with a capture group by enclosing that part
with \(
and \)
, matching the rest of the line (but not remembering it) and
then replacing the line with the remembered group using \1
:
:%s/\(fruit\).*$/\1/
With normal commands applied to range of lines
You could specify the lines you want to affect and give a normal mode command
to be applied to each line (see :help :normal
):
:1,3norm Sfruit
This means, for lines 1 to 3, apply the normal mode command Sfruit
, where S
means 'delete lines and start insert' and then you just type what you want on
the line (see :help S
).
With the global command
You can also apply normal commands to lines matched by some pattern (see :help global
):
:g/^fruit/norm wd$
This will apply only to lines with the word 'fruit' appearing at the start (you
can imagine more elaborate patterns in other scenarios). The normal mode
commands wd$
mean:
w " move cursor forward one word
d$ " delete until end of line
(although we could have used Sfruit
again)
With a macro
Another way would be to record a macro (see :help macro
) such as qa0wd$jq
(notice it uses the same method as above). You can then replay the macro with
@a
and repeat it many times with @@
, or apply it to all lines with :%norm @a
(or you could use a range/pattern to specify the lines like above). This
breaks downs as follows:
qa " start recording macro into the 'a' register
0 " move cursor to the beginning of the line
w " move cursor forward one word
d$ " delete until end of line
j " move cursor down to the next line
q " finish recording the macro
With block selection
You can also select the words you want by switching to visual block mode with
Ctrl
+v
(see :help visual-block
), highlighting the part of the file you
don't want with regular vim motions (you can press o
to put the cursor on the
other/opposite corner of the selection block) and finally pressing d
to
delete the selected content