Skip to content

Linux Foundations / Find your way around Linux ยท Step 53 of 63

Lesson: Vim EditingSwitch
โ† Linux Foundations

Shell and files

Vim Editing

Delete, change, copy, paste, undo and replace text from Vim's Normal mode.

Most editing in Vim happens in Normal mode, without typing any new text. Press Esc first.

Deleting

  • x deletes the character under the cursor.
  • dd deletes the whole line.
  • dw deletes from the cursor to the start of the next word.
  • D or d$ deletes to the end of the line.

The pattern is "operator plus motion": d says what to do, and the motion says how far. A count works too, so 3dd deletes three lines.

Changing

c works like d but leaves you in Insert mode afterwards. cw changes a word and cc changes a whole line. Type the new text and press Esc.

Copying and pasting

Vim calls copying "yanking".

  • yy yanks the current line.
  • yw yanks a word.
  • p puts the text after the cursor, or below the line for whole lines.
  • P puts it before, or above.

Deleted text is kept as well, so dd followed by p moves a line down by one.

To select first and act second, press v for characters or V for whole lines, move, then press d, c or y.

Vim's internal registers are separate from your desktop clipboard in many setups, so a yank may not be available in other programs.

Undo and redo

  • u undoes the last change.
  • Ctrl-r redoes it.

In full Vim you can press u repeatedly to go further back. In original vi behaviour, which some minimal builds follow, a second u reverses the first one instead.

Search and replace

The substitute command is typed after a colon:

vim
:s/http/https/
:s/http/https/g
:%s/http/https/g
:%s/http/https/gc

Without a range, :s works on the current line only, and changes just the first match. The g flag changes every match on the line. % means every line in the file. The c flag asks you to confirm each one: answer y or n, or q to stop.

If your text contains slashes, use another separator:

vim
:%s#/var/www#/srv/www#g

Two small extras: J joins the next line onto the current one, and . repeats the last change.

Try it

  1. Create a file: printf 'one http\ntwo http http\nthree\n' > edit.txt.
  2. Open it with vim edit.txt.
  3. Press dd, then p, and watch the first line move down.
  4. Press u to undo the paste, then u again to undo the delete (full Vim).
  5. Run :%s/http/https/g.
  6. Save with :wq and check with cat edit.txt.

For a live Linux shell, there is the permissions lab.

Check your understanding

Vim Editing

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.