Vi editor question

in Vi how do I delete part of a line ( leave few words in a line and delete rest of the line )

Hmm. I use "dw" (delete word ) repeatedly to remove chunks of text. If someone else has a better choice I'd like to know, too.
yank does one or more whole lines, so it won't work.

You can use "d $" to delete from the current cursor position to the end of the line. AFAIK there is no way to remove a chunk of text from the middle of the line, except with X,x, or dw

See the vi cheat sheet:
Vi Cheat Sheet

It accepts numbers before as well.
e.g. 3dw will delete 3 words in line from cursor to the right.

Regards
Peasant.

Use D in command mode. It deletes the rest of the line from the cursor position.
Command C does the same but then switches to insert mode after deleting rest of the line so that you can start editing the line.

Hi.

In command mode d$ deletes to end-of-line, d0 deletes to beginning of line.

They are not quite symmetrical, d$ deletes the character under the cursor, d0 does not, but my fingers got used to the difference ... cheers, drl

1 Like

Last tip: as you already have been told "D" in command mode deletes from the cursor position to the end of line. To effectively put the cursor to the correct position you can use the "w" command, which moves you to the start character of the next word or "W" to put you to the start character of the next word separated by blanks. The difference is that some characters (i.e. ":", "-", etc.) are also recognized as word boundaries and in a line like this:

abc+def:ghi jkl-mno pqr

if you are at the first character, entering "w" consecutively will put you over the "+", the "d", the ":", the "g" etc.. Entering "W" instead will put you on the "j" first and the "p" next.

You can also use multipliers for these commands, so "4w" on the first character of the line will put you on the "g" immediately.

I hope this helps.

bakunin

Without a better explanation of what you're trying to do, it is hard to give a good answer.

If you want to delete all but the last 3 words on every line, or delete the first 2 words on every line, we can make suggestions that will help. If you want to delete everything but a few recognized words (and can't or won't tell us which words are "recognized"), it becomes much harder for us to make any useful suggestions.

If you can show us a representative sample input file and explain how you want to modify that text and show us the output you hope to produce, we can do a much better job of making useful suggestions.

1 Like