Как работать с vi в linux
Перейти к содержимому

Как работать с vi в linux

  • автор:

Основные команды текстового редактора VI / VIM

Текстовый редактор vim, созданный на основе более старого vi. Один из мощнейших текстовых редакторов с полной свободой настройки и автоматизации, возможными благодаря расширениям и надстройкам. По умолчанию входит в состав любого дистрибутива Linux.

Открываем файл с помощью vi / vim:

Основные режимы работы.

«Обычный режим» — перемещение по файлу, стирание текста и другие редактирующие функции. Это — основной режим, только из него можно сразу перейти в другие режимы. Для возврата в основной режим из любого другого режима:

«Режим ввода» — ввод текста. Как только завершается ввод текста, принято сразу возвращаться в обычный режим. Заметьте, что стирание и ввод текста происходит в двух разных режимах. Переход в него из обычного режима:

«Командный режим» — Команды (операции с файлом, поиск и замена, настройка редактора…). Переход в него из обычного режима:

«Режим поиска» — ввод поискового запроса. Переход в него из обычного режима

«Визуальный режим» — режим выделения текста:

Перемещение по файлу

После загрузки Vim, на экране вы увидите часть загруженного вами текстового файла. Загрузившись, Vim находится в «командном режиме» — один из основных режимов. Это значит, что если вы нажмете клавишу <l> (строчная L), вместо появления «l» на месте курсора вы увидите, что курсор сдвинулся на один символ вправо. В командном режиме знаки, набираемые на клавиатуре, используются как команды для Vim, а не как помещаемые в текст символы. Команды перемещения — один из наиболее важных типов команд. Вот некоторые из них:

Ввод текста

Следующие команды переводят редактор в режим ввода:

Удаление и вставка

Ниже перечислены основные комманды удаления и вставки текста:

Отмена изменений

Поиск

Перейти на строку:

Выход

Есть еще пара команд, которые вам необходимо знать:

В этой статье описаны основные возможности, необходимые для работы. Практически во все дистрибутивы Linux входит учебник по работе с редактором, — просто введите в командной строке команду vimtutor.

05: VI Text Editor¶

In this chapter you will learn how to work with the VIsual editor.

Objectives : In this chapter, future Linux administrators will learn how to:

Use the main commands of the VI editor;
Modify a text with the VI editor.

user commands, linux

Knowledge:
Complexity:

Reading time: 20 minutes

Visual (VI) is a very popular text editor under Linux, despite its limited ergonomics. It is indeed an editor entirely in text mode: each action is done with a key on the keyboard or dedicated commands.

Very powerful, it is above all very practical since it is on the whole minimal for basic applications. It is therefore accessible in case of system failure. Its universality (it is present on all Linux distributions and under Unix) makes it a crucial tool for the administrator.

Its functionalities are:

  • Insert, delete, modify text;
  • Copy words, lines or blocks of text;
  • Search and replace characters.

vi command¶

The vi command opens the VI text editor.

Option Information
-c command Execute VI by specifying a command at the opening

If the file exists at the location mentioned by the path, it is read by VI which is placed in commands mode.

If the file does not exist, VI opens a blank file and an empty page is displayed on the screen. When the file is saved, it will take the name specified with the command.

If the command vi is executed without specifying a file name, VI opens a blank file and an empty page is displayed on the screen. When the file is saved, VI will ask for a file name.

The vim editor takes the interface and functions of VI with many improvements.

Among these improvements, the user has syntax highlighting, which is very useful for editing shell scripts or configuration files.

During a session, VI uses a buffer file in which it records all the changes made by the user.

NOTE: As long as the user has not saved his work, the original file is not modified.

At startup, VI is in commands mode.

TIP: A line of text is ended by pressing ENTER but if the screen is not wide enough, VI makes automatic line breaks, wrap configuration by default. These line breaks may not be desired, this is the nowrap configuration.

To exit VI, from the Commands mode, tap : then type:

  • q to exit without saving (quit);
  • w to save your work (write);
  • wq (write quit) or x (eXit) to save and exit.

To force the exit without confirmation, you must add ! to the previous commands.

WARNING: There is no periodic backup, so you must remember to save your work regularly.

Operating mode¶

In VI, there are 3 working modes:

  • The command mode;
  • The insertion mode;
  • The ex mode.

The philosophy of VI is to alternate between the command mode and the insertion mode.

The third mode, ex, is a footer command mode from an old text editor.

The Command Mode¶

This is the default mode when VI starts up. To access it from any of the other modes, simply press the ESC key.

All entries are interpreted as commands and the corresponding actions are executed. These are essentially commands for editing text (copy, paste, undo, . ).

The commands are not displayed on the screen.

The Insert mode¶

This is the text modification mode. To access it from the command mode, you have to press special keys that will perform an action in addition to changing the mode.

The text is not entered directly into the file but into a buffer zone in the memory. The changes are only effective when the file is saved.

The Ex mode¶

This is the file modification mode. To access it, you must first switch to command mode, then enter the ex command frequently starting with the character : .

The command is validated by pressing the ENTER key.

Moving the cursor¶

In command mode, there are several ways to move the cursor.

The mouse is not active in a text environment but is in a graphic environment, it is possible to move it character by character, but shortcuts exist to go faster.

VI remains in command mode after moving the cursor.

The cursor is placed under the desired character.

From a character¶

  • Move one or n characters to the left:

[ ← ], [ n ][ ← ], [ h ] or [ n ][ h ]

  • Move one or n characters to the right:

[ → ], [ n ][ → ], [ l ] or [ n ][ l ]

  • Move one or n characters up:

[ ↑ ], [ n ][ ↑ ], [ k ] or [ n ][ k ]

  • Move one or n characters down:

[ ↓ ], [ n ][ ↓ ], [ j ] or [ n ][ j ]

  • Move to the end of the line:
  • Move to the beginning of the line:

From the first character of a word¶

Words are made up of letters or numbers. Punctuation characters and apostrophes separate words.

If the cursor is in the middle of a word [ w ] moves to the next word, [ b ] moves to the beginning of the word.

If the line is finished, VI goes automatically to the next line.

  • Move one or n words to the right:
  • Move one or n words to the left:

From any location on a line¶

  • Move to last line of text:
  • Move to line n :
  • Move to the first line of the screen:
  • Move to the middle line of the screen:
  • Move to the last line of the screen:

Inserting text¶

In command mode, there are several ways to insert text.

VI switches to insert mode after entering one of these keys.

NOTE: VI switches to insertion mode. So you will have to press the ESC key to return to command mode.

In relation to a character¶

  • Inserting text before a character:
  • Inserting text after a character:

In relation to a line¶

  • Inserting text at the beginning of a line:
  • Inserting text at the end of a line:

In relation to the text¶

  • Inserting text before a line:
  • Inserting text after a line:

Characters, words and lines¶

VI allows text editing by managing:

  • characters,
  • words,
  • lines.

In each case it is possible to :

  • delete,
  • replace,
  • copy,
  • cut,
  • paste.

These operations are done in command mode.

Characters¶

  • Delete one or n characters:
  • Replace a character with another:
  • Replace more than one character with others:

[ R ][ characters ][ ESC ]

NOTE: The [ R ] command switches to replace mode, which is a kind of insert mode.

Words¶

  • Delete (cut) one or n words:

[ d ][ w ] or [ n ][ d ][ w ]

  • Copy one or n words:

[ y ][ w ] or [ n ][ y ][ w ]

  • Paste a word once or n times after the cursor:
  • Paste a word once or n times before the cursor:
  • Replace one word:

[ c ][ w ][ _word_ ][ ESC ]

TIP: It is necessary to position the cursor under the first character of the word to cut (or copy) otherwise VI will cut (or copy) only the part of the word between the cursor and the end. To delete a word is to cut it. If it is not pasted afterwards, the buffer is emptied and the word is deleted.

VI / VIM editor

VI / VIM is a simple and powerful editor. If you are accessing a remote workstation or cluster where you don't have the option to launch graphical programs, VIM is a great option. Almost any Linux or UNIX system has VI editor preinstalled. Recent OS will likely have VIM (Vi IMproved) instead of classic VI editor. You can check the version of VI by:

In case it is not installed in your system, you can install using a package manager:

  • Open / create a file_name to read and/or write:
  • Go into INSERT mode by (check in the bottom of the window for —INSERT— ) by pressing [shift] + [I] or simply [I] .

Go into REPLACE mode (check in the bottom for —REPLACE— ) by pressing [shift] + [R] .

Go into readonly / normal mode by pressing [esc] .

To save file, first go into readonly mode ( [esc] ) and then type:

  • To exit vim, first go into readonly mode ( [esc] ) and then:
  • You can combine both to save and exit (keyboard shortcut [Shift] + [Z Z] ):
  • Exit without saving (keyboard shortcut [Shift] + [Z Q] ):

Search in the file: Type / followed by the phrase you are looking for. Press N go to next match. You can search backwards using ?

See line numbers: :set nu

Hide line numbers: :set nonu

Spellcheck: :set spell

Turn off spellcheck: :set nospell

Set user spell file: :set spellfile=

Browse files and folders using file explorer: :E

Keyboard shortcuts​

  • Compare two files:
  • Move a line up / down: this can be achieved by few key combinations. To move one line above its current position: ddkP .
    • dd to delete current line and put it in default register
    • k or j to move up or down
    • P to paste above current line.

    visual mode​

    Enter Visual mode by pressing v , V or [control] + v for visual character, line or block modes, respectively. Select text using the arrow keys on the key board. You can:

    Press c it will clear the selected part and enter into insert mode.

    Press y to copy (yanked).

    You can paste in another location in VIM by pressing p .

    Press "+y to copy to system clipboard, you can paste in another program using your system shortcut like [command] + v or [control] + v .

    How to use vi editor?

    devopsfunda

    Linux peoples commonly use vi editor. vi/vim editor is a command line editor. Vim is a text editor that is upwards compatible to Vi. It can be used to edit all kinds of plain text. It is especially useful for editing programs.

    Starting vi/vim

    ENTERING TEXT

    MOVING THE CURSOR

    BASIC EDITING

    MOVING AROUND IN A FILE

    CLOSING AND SAVING A FILE

    SEARCHING and REPLACING

    The formal syntax for searching is:

    The syntax for replacing one string with another string in the current line is

    Here “pattern” represents the old string and “replace” represents the new string.

    The syntax for replacing occurrence of a string in the text is similar. The only difference is the addition of a “%” in front of the “s”:

    To undo recent changes, from normal mode use the undo command:

    u undo last change (can be repeated to undo preceding commands)

    Ctrl-R Redo changes which were undone (undo the undos). Compare to . to a previous change, at the current cursor position. Ctrl-R (hold down Ctrl and press r) will redo a previously undone change, wherever the change occurred.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *