- Gray at the temples and in need of reading glasses, the middle-aged Vi (pronounced vee-eye) editor, released in 1976, is still a system administrator’s best friend.
- Чаще всего при запуске vi (утилита еще со времен UNIX) запускается по факту vim (VI imporoved) за счет alias – напр. MacOS
bash-3.2$ ls -ltr /usr/bin/vi lrwxr-xr-x 1 root wheel 3 Feb 29 07:05 /usr/bin/vi -> vim
- Если на сервере нет vim (есть только vi), возможно есть vim.tiny (на примере Debian). Это частое явление, в таких сборках обычно отключается подсветка синтаксиса для множества языков в сравнении со стаднартным vim.
vim.tiny /etc/network/interfaces
- Vi/vim из коробки, в отличии от vim.tiny зачастую (не всегда) не позволяет вставлять текст из gui, что крайне неудобно. В таком случае можно использовать команду :set paste и после нее вставлять.
More info
- .vimrc – тут хранятся настройки по умолчанию которые применяются при запуске vim. Если файл пустой то старт с дефолтными настройками. Пример настроек есть в файле .vimrc /usr/share/vim/vim74/vimrc_example.vim. Тут можно, например, сразу включить нумерацию строк по set number.
- книги про VIM
- man vim
- vimtutor – обучалка основам vim примерно на пару часов (хотя они и пишут 20-30 минут).
-
<F1>, :help – открываем внутри VIM встроенный HELP. Переключаться между основным документом и HELP-документом можно через CTRL-W, закрыть документ можно :q.:help <FIND> (help hls; :help user-manual) – поиск в help. Из под root и из vimtutor поиск в Help не работает.
- :help user-manual
Start
Modes
Commands
Change mode
Delete
dG – удалить все ниже текущей строки
Move pointer
COPY/PASTE
shift + insert – из буфера (clipboard)
y – copy operator. Можно использовать в visual mode, на строки (yy, y$), можно на слова (y2w). 17yy – скопировать текущую строку и 16 ниже (всего 17), подробнее ниже в вопросах.
CHANGE / find-replace
UNDO/REDO
FIND
vi +/pattern test.sh
SAVE & QUIT
As akshay pointed out, Vim's documentation explains, that:x
andZZ
are equivalent and only save a file if the associated buffer has been changed. Whereas:wq
saves the buffer to the corresponding file, even if it is unchanged. In both cases, the contents of the buffer will be saved to disk. Obviously the outcome is the same, so why bother, right? But wait... There is a subtle, but not irrelevant difference. If you exit Vim via:x
and there has been no change to the buffer, there will be no change to the modification time of that file. On the other hand, if you quit via:wq
, the modification time will change, as the file is technically rewritten (saved again). This can have some impact in certain situations. For example a backup process that is dependent on modification time, could store this file (and potentially send it over the network) even if no additional information has been included. Or some monitoring process could ring an alarm if it detects that (for it) the file has been changed...
OTHER
:set paste – для вставки текста из gui, не всегда нужно (см. выше)
:set number – нумерация строк в открытом файле, иногда включена по умолчанию, иногда нет, удобная вещь как для понимания где в файле находишься, так и для перемещения по файлу (:<number> переместит в нужную строку) и редактирования (:<number>d удалит строку, а :<number1,number2>d удалить диапазон строк).
questions
In the vi editor, what vi command will copy (but not paste) from the current line at the cursor and the following 16 lines (17 lines total)? Specify the correct vi command without spaces.
17yy Explanation The vi editor is a text editor that operates in two modes: command mode and insert mode. In command mode, the user can enter commands to perform various operations on the text, such as copying, pasting, deleting, moving, searching, etc. In insert mode, the user can type text into the file. To switch from command mode to insert mode, the user can press i, a, o, or other keys. To switch from insert mode to command mode, the user can press Esc. The yy command is used to copy (yank) the current line into a buffer. The number before the yy command specifies how many lines to copy, starting from the current line. Therefore, the command 17yy will copy the current line and the following 16 lines (17 lines total) into a buffer. The buffer can then be pasted into another location by using the p or P command. Note that the command 17yy does not paste the copied lines, it only copies them.
Which of the following vi commands deletes two lines, the current and the following line?
A. d2
B. 2d
C. 2dd
D. dd2
E. de12
Answer: C
When in Normal mode invi, which character can be used to begin a reverse search of the text?
A. ?
B. /
C. F
D. r
Correct Answer: A In vi, the ? character can be used to begin a reverse search of the text. This means that the search will start from the current cursor position and move backwards towards the beginning of the file. The search pattern can be any regular expression that matches the desired text. To repeat the search, the user can press n for the previous match or N for the next match. The / character can be used to begin a forward search of the text, which means that the search will start from the current cursor position and move forwards towards the end of the file. The F and r characters are not used for searching, but for other commands in vi. The F command is used to move the cursor to a previous occurrence of a specified character in the current line. The r command is used to replace the character under the cursor with another character.
While editing a file in vi, the file changes due to another process. Without exiting vi, how can the file be reopened for editing with the new content?
A. :r
B. :n
C. :w
D. :e
Answer: D Explanation The :e command in vi is used to edit a file. If the file name is not specified, it will edit the current file. If the file has been changed by another process, the :e command will reload the file with the new content, discarding any unsaved changes made in vi. Therefore, the :e command can be used to reopen the file for editing with the new content without exiting vi. The other options are either invalid or do not perform the desired task. The :r command is used to read the content of another file or command and insert it into the current file. The :n command is used to edit the next file in the argument list, if any. The :w command is used to write the current file to disk, optionally with a new name.
In the vi editor, how can commands such as moving the cursor or copying lines into the buffer be issued multiple times or applied to multiple rows?
A. By using the command :repeat followed by the number and the command.
B. By specifying the number right in front of a command such as 4l or 2yj.
C. By selecting all affected lines using the shift and cursor keys before applying the command.
D. By issuing a command such as :set repetition=4 which repeats every subsequentcommand 4 times.
Answer: B
Which of the following are modes of the vi editor? (Choose two.)
A. edit mode
B. insert mode
C. change mode
D. review mode
E. command mode
Answer: BE The Vi editor has two modes: Command and Insert. https://www.redhat.com/sysadmin/introduction-vi-editor
Immediately after deleting 3 lines of text in vi and moving the cursor to a different line, which single character command will insert the deleted content below the current line?
A. i (lowercase)
B. P (uppercase)
C. p (lowercase)
D. U (uppercase)
E. u (lowercase)
Answer: C
In vi editor, the command to delete a line of text is "dd". So, if we want to delete 3 lines of text, we can type "3dd". After deleting the text, if we want to insert it below the current line, we can use the "p" command. The "p" command stands for "put" and it will insert the deleted text below the current line.
For example, let's say we have the following text in vi:
Line 1 Line 2 Line 3 Line 4
If we want to delete lines 2, 3, and 4, we can type "3dd" while the cursor is on line 2. The text will now look like this:
Line 1
The deleted text is now in the buffer, ready to be put back in the file. If we want to insert the deleted text below line 1, we can move the cursor to line 1 and type "p". The text will now look like this:
Line 1 Line 2 Line 3 Line 4
Option A (i) is the command to enter insert mode, which is not relevant to this scenario.
Option B (P) is the command to put the deleted text above the current line.
Option D (U) is the command to undo the last action, which would undo the deletion of the text.
Option E (u) is the command to undo the last action for a single line, which would also undo the deletion of the text.