1. Introduction to VI Editor
The vi editor is a standard Unix and Linux Text editor with a relatively lightweight but powerful Text editor. It was invented in the 1970s, making it one of the first Text editors meant for Unix. Vi operates entirely through the keyboard, using specific commands for all functions; it is unlike graphical editors. It can feel daunting at first, but users love that it’s so efficient for managing remote servers or big files once you get the hang of it. Its modal editing style is unique: Commands, Inserting Text, managing files, and vi have separate modes. This approach well serves complex tasks, and so vi is an important tool for anyone who ever works with Linux.
Installation
Though most Linux systems come with vi editor pre-installed, some users may find they need to install it if it’s missing manually.
Installation on Linux Distributions
Ubuntu/Debian:
sudo apt update
sudo apt install nvi -y
- RockyLinux/AlmaLinux:
sudo yum install vi -y
- Fedora:
sudo dnf install vi -y
- Arch Linux:
sudo pacman -S ex-vi
- OpenSUSE:
sudo zypper install ex-vi
Usage:. Use the vi editor filename to open a file with the standard vi editor.
Modes in vi Editor:
- Command Mode: For navigation and Text manipulation.
- Insert Mode: For typing and editing Text.
2. Getting Started with VI Editor
Launching and closing the vi editor might feel different from traditional editors, as the vi editor does not immediately let you start typing. When you open a file, you begin in Command Mode, which is for navigation and editing commands. Switch to Insert Mode by pressing i, To enter Text. When you’re ready to save, you can use: w to write changes and: q to quit. Combining these: wq saves and exits, while: q! exits without saving. It’s common for new users to remain in Command Mode accidentally, so remember that pressing i (Insert) and Esc (back to Command) are your primary mode switches.
Launching and Closing VI Editor
Open a file in vi with:
vi filename
Key commands:
- :wq — Save and Exit.
In vi editor, the command :wq is used to save changes and Exit the editor. This command combines two actions: w writes (saves) your changes to the file, and q quits the editor. Such functionality is particularly useful for saving your edits before exiting the vi editor, ensuring your changes are securely stored. To use it, enter Command Mode (press Esc if needed), then type :wq and hit Enter. This command is an efficient way to wrap up your editing session, preserving changes and closing the file in one step.
- :q! — Exit without saving.
The :q! command in the vi editor allows you to Exit without saving any changes. It will come in handy when you want to discard any edits you’ve made. To use it, ensure you’re in Command Mode by pressing Esc, then type :q! and hit Enter. This command forcefully quits the vi editor, discarding any unsaved changes. It’s a quick way to close the editor without affecting the original file, especially handy when experimenting with edits or reviewing content without needing to save.
- :w — Save without exiting.
In vi editor, the command :w allows you to save your changes without closing the editor. It is helpful for keeping your progress periodically while still working on the file. To use it, make sure you’re in Command Mode by pressing Esc, then type :w and hit Enter. This command writes (saves) the changes you’ve made so far but keeps vi editor open, allowing you to continue editing. It’s a great way to ensure your work is saved without interrupting your workflow.
Switching Modes
- Command Mode: Press Esc.
- Insert Mode: Press i to start editing and Esc to stop.
3. Navigating Within Files
Navigating large files in vi editor is all about learning efficient keystrokes. The basic commands (h, j, k, l) are for moving left, down, up, and right, respectively. To jump to the start or end of a line, use 0 and $. For faster file navigation, gg takes you to the beginning, while G takes you to the end. If you’re looking for specific Text, the /pattern search is very handy. After finding the term, Use n
to move to the next occurrence and N
to go back to the previous one. Navigation becomes intuitive with practice for users dealing with long files like logs or code.
Basic Movement
- h, j, k, l — Move left, down, up, right.
H:
One character to the left of the cursor, the h command in vi editor, moves. Precise navigation within a line is used while adjusting the cursor position without any use of arrow keys. It keeps your hands on the home row, keeping you a close distance from the line of Text, allowing you to backtrack along it quickly. By practicing h alongside other movement keys (j, k, l), users can navigate through Text without shifting between the keyboard and mouse. With such an approach, you can take advantage of all the vi editor editing features without the worry of accidentally erasing what you’re editing.
J:
The j command moves the cursor down one line. Such navigation is a core part of vi editor basic controls, enabling users to move the cursor vertically without relying on the arrow keys. By repeatedly pressing j, you can scroll through using lines, which helps you review content, review other sections, or edit the file. The j command makes fingers stay on the home row, and vi editor can be moved quickly and consistently.
K:
The k command in vi means that it moves the cursor up by one line. These are core vi navigation keys (h, j, k, l) designed to keep your hands on the home row of the keyboard. When you press k, you can go up by a line very quickly, moving your cursor up in the document so you can go back to previous lines and change things above where your current position is. When you want to review or edit content above the cursor, this movement key helps. Vi teaches itself this: learning to use k together with any other navigation command will make file navigation in vi a lot faster.
L:
The l is a command in vi that moves one character to the right. The basic movement controls in vi are h, j, and k, alongside this command. Users can use l to position the cursor horizontally across Text, as l may be used to edit and position precisely. It’s easier from the keyboard to use, eliminating the need to use the arrow keys to access the Text. This command is handy when you need to do incremental movement of editing Text in Text line by line.
Line Navigation
- 0 — Start of line.
- $ — End of line.
- gg — Start of file.
- G — End of file.
The G command in vi lets you jump straight to the end of the file, making it ideal for quickly reaching the final lines in long documents. In the first image, the cursor starts at the beginning of the file. After pressing G, as shown in the second image, it instantly moves to the last line, allowing easy access for editing or review. You can also use a specific line number with G (e.g., 10G), which moves the cursor to line 10, enhancing navigation control.
Searching
- /pattern — Search forward.
In vi, the /pattern command allows you to search forward through the Text for a specific word or phrase. To use it, press / in Command Mode, type the desired Text or pattern, and hit Enter. vi will highlight the first match after the cursor. Pressing n will take you to the next occurrence, while N goes to the previous one. This search feature is helpful for locating specific content within large files, making it easier to find and edit particular words or sections.
- ?pattern — Search backward.
The ?pattern command in vi allows you to search backward through the Text for a specific word or phrase. To use it, press ? in Command Mode, type the pattern you’re looking for and press Enter. vi will locate the first occurrence of the pattern before the cursor’s current position. You can navigate through matches by pressing n to find the previous occurrence and N to find the next one. This backward search is particularly helpful when reviewing or editing earlier sections of a file.
- n / N — Next/previous occurrence.
In vi, after performing a search with /pattern (forward) or ?pattern (backward), you can use n and N to navigate between occurrences. Pressing n moves to the next match in the direction of the original search. Pressing N takes you to the previous match, reversing the search direction. These commands make it easy to jump through all instances of a term, helping with quick reviews and edits across large files.
4. Editing Text in VI
Editing commands make vi a powerful tool for modifying Text on the fly. To delete Text, you can use x
to remove a single character, dd
to delete an entire line, and dw
to delete from the cursor to the end of a word. Inserting Text can happen at different positions: i to insert at the cursor, a to add Text after the cursor, I to insert at the line’s start, and A to append at the line’s end. You can also change Text with commands like cw for word changes and cc for changing an entire line. These tools make vi efficient for both small edits and major revisions.
Deleting and Inserting Text
- x — Delete character.
In vi, the x command is used to delete the character under the cursor. Each time you press x in Command Mode, the character directly beneath the cursor is removed, allowing for precise, single-character deletions. This command is useful for quick corrections without entering Insert Mode, especially when you need to make small adjustments in Text or code. It’s a simple yet powerful way to clean up Text one character at a time.
- dd — Delete line.
The dd command in vi is used to delete an entire line where the cursor is positioned. By pressing dd in Command Mode, the line is removed from the Text, making it useful for quick deletions without having to select Text manually. This command is handy for removing multiple lines in sequence (e.g., 3dd deletes three lines). It’s an efficient way to manage Text, especially when working with code or configuration files where precise line control is needed.
- dw — Delete word.
In vi, the dw command deletes a word from the cursor position to the end of the word. You can do this in Command Mode by pressing dw
, which deletes the current word along with any spaces leading to the next word. It’s especially helpful for quick deletions without switching to Insert Mode, allowing you to remove unwanted words or phrases efficiently. You can also use it repeatedly (e.g., 2dw) to delete multiple words in sequence, making editing faster and more precise.
Inserting and Changing Text
- i, a, I, A — Insert at different positions.
I:
The i command in vi allows you to enter Insert Mode at the cursor’s exact position, letting you insert Text precisely where the cursor currently rests. Press i in Command Mode to start typing, and vi will shift into Insert Mode so you can add Text immediately. This command is useful for quick modifications within a line, especially when you need to insert characters or words within existing Text. To return to Command Mode, press Esc after your changes are complete.
A:
The command in vi is used to append Text right after the cursor’s current position. Unlike i, which inserts at the cursor, a moves the cursor one space forward before entering Insert Mode. It is especially useful for inserting Text directly after a specific character or word without manually repositioning the cursor. After completing your input, press Esc to Exit insert mode and return to command mode.
I:
The I command in vi allows you to enter Insert Mode at the start of the current line, regardless of where the cursor is currently positioned. Pressing I in Command Mode places the cursor at the beginning of the line, ready for you to type. Such a method offers a quick and convenient way to add Text or make adjustments at the beginning of a line without manually navigating there first. After making your edits, press Esc to return to Command Mode.
A:
The A command in vi is used to append Text at the end of the current line. When you press A in Command Mode, vi moves the cursor to the end of the line and switches to Insert Mode, allowing you to add Text immediately after the line’s last character. Such an approach is especially helpful for appending comments or extensions to the end of a line without additional navigation. Once done, press Esc to Exit Insert Mode and return to Command Mode.
- cw, c$, cc — Change Text from the cursor position.
Cw:
The cw command in vi is used to change (replace) Text from the cursor position to the end of the current word. Press cw in Command Mode, and vi deletes the Text from the cursor to the end of the word, allowing you to start typing immediately in Insert Mode. This one is handy when you want to quickly replace the individual word with a new word without having to delete and retype the words. After entering the new Text, hit Esc in order to return to Command Mode.
c$:
The c$ command in vi allows you to change all Text from the cursor’s position to the end of the line. Pressing c$ in Command Mode deletes the Text from the cursor onward, switching to Insert Mode so you can replace it immediately. Such functionality is particularly valuable for quickly editing or replacing large sections of a line. After typing the new content, press Esc to Exit Insert Mode.
Cc:
The cc command in vi deletes the entire line where the cursor is positioned and places you in Insert Mode to type a new line immediately. Pressing cc in Command Mode clears the line’s contents, making it ready for replacement. This command is convenient when you want to replace a line’s content entirely without manually deleting each part. After adding your new Text, press Esc to return to Command Mode.
5. Advanced Editing Techniques
Advanced editing functions in vi enable complex Text manipulation. Copying lines, or “yanking,” is done with yy, while p pastes it below the cursor, and P pastes it above. Undo and redo are handled with u and Ctrl + r, respectively. Global find and replace is also simple, using :%s/old_text/new_text/g to replace Text throughout a file. Each command can be refined to target specific sections, making it invaluable for projects involving repetitive edits, such as configuration files or scripts. Mastering these commands increases productivity when managing and modifying Text.
Copying and Pasting
- yy — Yank (copy) line.
In vi, the yy command is used to copy (or “yank”) the entire line where the cursor is positioned. Pressing yy in Command Mode places the line in vi’s buffer, ready to be pasted elsewhere. This command is useful for duplicating lines, moving content around, or quickly replicating similar sections of Text. After yanking a line, you can paste it by positioning the cursor where you want the copied line to appear and pressing p to paste below the cursor or P to paste above it.
- p / P — Paste after/before the cursor.
Pasting Text After the Cursor with p
In vi, the p command pastes Text after the cursor’s current position. When you’ve yanked (copied) or deleted Text, press p in Command Mode to insert the Text directly below the cursor line if it’s a whole line or immediately after the cursor if it’s a character or word. This command is useful for quickly duplicating or repositioning content within your file.
Pasting Text Before the Cursor with P
The P command in vi pastes Text before the cursor’s current position. Use P in Command Mode to place yanked or deleted Text directly above the cursor line if it’s a full line or just before the cursor if it’s a character or word. This command is helpful for inserting content just before the current line or character without extra navigation steps.
Undo and Redo
- u — Undo the last change.
The u command in vi lets you undo the last change you made to the file. Pressing u in Command Mode reverses the most recent edit, whether it’s a Text insertion, deletion, or formatting change. This command is essential for quickly correcting mistakes without needing to re-edit the Text. You can repeatedly press u to continue undoing earlier changes step-by-step. If you need to redo an undo, you can press Ctrl + r to revert to the previous state.
- Ctrl + r — Redo.
In vi, the Ctrl + r command is used to redo the last undone change. After using u to undo an edit, pressing Ctrl + r in Command Mode will reapply that change, effectively “redoing” it. This command is useful when you’ve undone a change and then decide to keep it after all. Ctrl + r lets you navigate between your recent changes and corrections without re-editing Text manually.
Find and Replace
- :s/old/new/ — Replace the first occurrence on the line.
In vi, The first instance of a given Text pattern on a line can be changed or replaced by the command s/old/new/. Here’s how it works: type :s/old/new/ in Command Mode, replacing “old” with the Text you want to find and “new” with the replacement Text. vi will locate the first match on the line and replace it with your specified Text, leaving any additional occurrences on the line unchanged. This command is helpful for making targeted edits without affecting repeated terms on the same line. Hit Enter after entering the command to carry out the replacement.
- :s/old/new/g — Replace all on the line.
In vi, the command :s/old/new/g is used to replace every occurrence of a specified Text pattern on the current line. To execute, type :s/old/new/g in Command Mode, substituting “old” with the Text you want to replace and “new” with the replacement Text. Adding the g flag ensures that all instances of “old” on the line are replaced, not just the first one. This command is particularly useful when a word or phrase appears multiple times on a line and needs to be updated consistently. Press Enter to apply the changes.
- :%s/old/new/g — Replace in the entire file.
The command :%s/old/new/g in vi allows you to replace every occurrence of a specific Text pattern throughout the entire file. In Command Mode, type :%s/old/new/g, replacing “old” with the Text you want to find and “new” with the replacement Text. The :%s part specifies that the command should apply to every line, while the g flag ensures all instances in each line are replaced, not just the first. This command is ideal for making global edits across a file, such as updating variable names or correcting repeated Text throughout the document. Press Enter to execute.
6. Working with Multiple Files
vi allows users to work with multiple files in one session. Use vi file1 file2 to open multiple files at once, then switch between them with :n for the next file and :prev for the previous one. You can split windows horizontally with :split filename or vertically with :vsplit filename, providing a side-by-side view of two files. Tabs are also available in vi for those who prefer tabbed file management; open a new tab with :tabnew filename. This flexibility helps with cross-referencing content or making consistent edits across multiple files in real-time.
Opening and Switching
vi file1 file2
:n / :prev — Move to next/previous file.
n vi, the commands :n and :prev allow you to navigate between multiple open files in a single session. When you open several files at once (e.g., vi file1 file2 file3), you can type :n in Command Mode to move to the next file in the sequence. Conversely, :prev will take you to the previous file. These commands are useful for working across multiple files without closing and reopening vi, making it easy to switch back and forth for tasks like comparing content or making consistent edits. Hit Enter after each command to apply the switch.
Split Windows
- :split filename — Horizontal split.
In vi, the command :split filename opens a specified file in a horizontal split, allowing you to view and edit two files or sections side by side. To use this feature, type :split filename in Command Mode, replacing “filename” with the name of the file you want to open in the split. This command is especially helpful for comparing files or referencing one file while editing another. The screen will divide horizontally, with each file displayed in its window. You can navigate between the splits by pressing Ctrl + w twice.
- :vsplit filename — Vertical split.
In vi, the :vsplit filename command opens a specified file in a vertical split, displaying two files side by side for easier comparison or simultaneous editing. To use it, type :vsplit filename in Command Mode, replacing “filename” with the name of the file you wish to open. The screen will divide vertically, creating a separate column for each file. This setup is helpful when you need to reference or edit two files without switching back and forth. To navigate between the split windows, press Ctrl + w twice.
Tabs
- :tabnew filename — Open file in a new tab.
In vi, the :tabnew filename command opens a specified file in a new tab, allowing you to work on multiple files in separate tabs within the same session. To use this command, type :tabnew filename in Command Mode, replacing “filename” with the file you wish to open. Each tab acts as an individual workspace, which can be useful for organizing files independently without cluttering the main screen. You can switch between tabs using gt to move forward or gT to move backward, enhancing multi-file management.
- :tabclose — Close tab.
In vi, To close the current tab we use the tabclose command. Such a feature is helpful in case you still need to finish and would like to close the file in a separate tab afterward without leaving your workspace messy. To close a tab, simply type :Then press tabclose to get into Command Mode and then press Enter again. This action will close your active tab without affecting other open tabs or files in your vi session, which is handy for dealing with many files in one go.
7. Customizing VI with Advanced Commands
Customizing vi to suit your workflow can make editing more comfortable. Options like :set number display line numbers are useful when editing scripts or code. If you’re working on case-sensitive Text, enabling :set ignorecase makes searches case-insensitive, allowing easier navigation through content. You can also record macros with q, which are keyboard shortcuts you create by recording a sequence of actions under one key. Later, run the macro with @ followed by the assigned letter. This feature is a powerful time-saver for repetitive editing tasks.
Useful Options
- :set number — Show line numbers.
The :set number command in vi enables line numbering for the entire document, displaying a line number to the left of each line. This feature is special because it makes it much easier to reference specific lines of code for edits, debugging, or collaboration when working with large files. To activate it, type :set number in Command Mode and press Enter. The line numbers appear immediately, and to disable them, you can use the :set number command. Line numbering provides a clear structure, especially when working on code or configuration files.
- :set ignorecase — Case-insensitive search.
The :set ignorecase command in vi allows for case-insensitive searching, meaning searches will match Text regardless of uppercase or lowercase letters. To enable it, type :set ignorecase in Command Mode and press Enter. This setting is useful when you want to find all occurrences of a word or phrase without worrying about capitalization. For instance, searching for “example” will match “Example,” “EXAMPLE,” and any other case variations. If you need to revert to a case-sensitive search, use :set noignorecase. This feature simplifies locating Text across diverse capitalization styles.
- :set wrap — Enable line wrapping.
The :set wrap command in vi enables line wrapping, making long lines of Text wrap onto the next line within the editor view. This functionality is especially useful when the Text or code you are working with is longer than the screen width, and it keeps all the content in view without having to scroll horizontally. To activate line wrapping, type :set wrap in Command Mode and press Enter. It automatically wraps on the edge of the window. If you prefer to view long lines without wrapping, use :set nowrap to turn off this feature.
Using Macros
- Start recording with a q+ letter.
- Execute commands.
- Stop with q.
- Play with the @ + letter.
8. VI Shortcuts and Tips
Buffers
- :ls — List buffers.
In the Vi editor, the `:ls` command is used to list all currently open buffers, which are the in-memory representations of files you are working on. Each buffer is assigned a unique number and may include information about its status, such as whether it is active (indicated by `%`), hidden (`#`), or unnamed. At the same time, it gives you a clear overview of your editing sessions, so switching between files becomes easier. You can navigate to a specific buffer using `:buffer <number>`, enhancing workflow efficiency by allowing quick access to multiple files without closing any.
- :buffer [number] — Switch buffers.
The `:buffer [number]` command in the Vi editor allows you to switch to a specific buffer using its unique number. Buffers represent open files or editing sessions, and this command makes it easy to navigate between them. For instance, if you list buffers with `:ls` and see a buffer numbered 2, you can switch to it by typing `:buffer 2`. This command is essential for multitasking, as it enables quick access to different files without needing to close or reopen them, streamlining your editing process and improving overall efficiency in handling multiple documents.
Bookmarks
- m[a-z] — Set a bookmark.
In the Vi editor, the command `m[a-z]` is used to set a bookmark (or mark) at the current cursor position. The lowercase letter `[a-z]` represents a specific mark name, allowing you to define up to 26 different bookmarks. For example, typing `ma` sets a mark named ‘a’ at the current location. You can later return to this mark by using the command `’a’, which jumps to the beginning of the line where mark ‘a’ is set. Such functionality allows you to navigate to key positions in your Text quickly, speeding up the editing process.
9. Troubleshooting Common Issues
A few common challenges in vi can be easily managed. If you get stuck in Command Mode, pressing Esc a few times brings you back to Normal Mode. If you need to Exit vi but can’t save, q! will Exit without saving changes. In cases where you try to save but get a permission error, w !sudo tee % allows you to save with elevated permissions. These troubleshooting steps can make vi feel less daunting, helping you navigate the editor confidently.
Common fixes:
- Stuck in Command Mode: Press Esc repeatedly.
- Exit without Saving: :q!.
The command :q! in the Vi editor is used to Exit the editor without saving any changes made to the current buffer. Here’s a breakdown:
- :q: This part of the command stands for “quit” and tells Vi to close the editor.
- !: The exclamation mark forces the quit action, overriding any warnings about unsaved changes.
When you type :q!, Vi will immediately close, discarding all modifications since the last save. This command is useful when you want to abandon changes or if you accidentally made edits you don’t want to keep. Always use it with caution, as it permanently loses unsaved work.
- Save with Permissions: :w !sudo tee %.
The command :w !sudo tee % in the Vi editor is a way to save changes to a file that you may not have permission to write to directly. Here’s a breakdown of how it works:
- :w: This part of the command indicates you want to write (save) the current buffer.
- !: This tells Vi to execute the following command in the shell instead of writing directly to the file.
- sudo: This allows you to run the command with superuser (administrator) privileges, enabling you to write to files that require higher permissions.
- tee: The standard input is taken by this command, and written to the standard output and the specified file.
- %: This represents the current file name in Vi.
So, when you run :w !sudo tee %, it saves the current buffer to the original file using elevated permissions, allowing you to bypass permission issues while saving your changes. After executing, you should confirm the operation by entering your password if prompted.
10. Conclusion
Learning to use the vi editor opens up new possibilities for managing and editing Text files directly in the Linux terminal. This guide has covered important vi commands, from navigation and editing basics to advanced features like macros, multiple file management, and custom configurations. With these tools, vi can become a powerful ally in your Linux workflow.
Tips for Practice and Mastery
- Start with the Basics: Focus on foundational commands like movement, Text insertion, and deletion. These are the building blocks of efficient vi use.
- Progress to Advanced Commands: Once comfortable with the basics, incorporate more complex features like search and replace, yanking, and multi-file editing.
- Expand Your Knowledge: Explore vi and try out plugins and other resources to gain vi broader capabilities to give vi more complexity.
Final Thoughts
With regular practice, Vi’s commands will become second nature, allowing you to work more quickly and confidently. Embrace the journey; each new command you learn makes vi a more powerful tool in your hands, simplifying even the most challenging text-editing tasks in Linux. Keep experimenting and refining your skills, and vi will soon feel like an extension of your Linux experience.
About the writer
This article was written by Vinayak Baranwal, For more insightful content or collaboration opportunities, feel free to connect with Vinayak on LinkedIn through the provided link.