Save with vi linux

How do I save files edited with vim?

If you are not comfortable with editing files in terminal based editors like vi or vim , I would recommend using graphical based editor like gedit to open them. Replace sudo vi with gksu gedit .

4 Answers 4

You’re probably in editing/insert mode. You need to type the following sequence :

  1. Esc , to quit edit mode and fallback to command mode ;
  2. : + w + q , start with a : (colon) then press w and finally q to write and quit (or just :w to write without quitting)
  3. then press Enter to valid.

I usually press ESC and then hold Shift and press z twice. Just like you would like to type two capital Z letters in word editor 🙂 That saves your document and closes your editor.

Oh man, shift and double z, what was the design logic behind that I wonder, «what’s the least intuitive command we can create?», ubuntu sometimes pisses me off like mad

@Sam, I just wanted to nitpick that vi has nothing in particular to do with ubuntu. Ubuntu was first released on 2004, while vi was created by Bill Joy around 1976, inspired by ed (dating back to 1971). This means that the shortcuts in vi predate those in almost any other still commonly used utility today. In a sort of coincidence, the first version of emacs, which has completely different weird shortcuts, was also released on 1976. Standardization efforts came much much later.

Wow thanks for the info @yoniLavi , my points is still the same though, so hopefully standardization efforts keep advancing.. 🙂

@Sam, vi keybindings are actually a lot more standard than you think; they’re virtually ubiquitous. Practically any program can be made to emulate vi keybindings. Even the default Gmail keybindings are obviously (to a Vim user) based off of vi keybindings.

Источник

Как сохранить файл в Vim / Vi и выйти из редактора

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

Читайте также:  Lotus note client linux

Vim или его предшественник Vi предустановлен на macOS и почти во всех дистрибутивах Linux. Знание основ Vim поможет вам, когда вы столкнетесь с ситуацией, когда ваш любимый редактор недоступен.

В этом руководстве объясняется, как сохранить файл в Vim / Vi и выйти из редактора.

Режимы Vim

Когда вы запускаете редактор Vim, вы находитесь в обычном режиме. В этом режиме вы можете использовать команды vim и перемещаться по файлу.

Чтобы ввести текст, вам необходимо войти в режим вставки, нажав клавишу i . Этот режим позволяет вставлять и удалять символы так же, как в обычном текстовом редакторе .

Чтобы вернуться в нормальный режим из любого другого режима, просто нажмите Esc .

Открыть файл в Vim / Vi

Чтобы открыть файл с помощью Vim, запустите терминал и введите vim а затем имя файла, который вы хотите отредактировать или создать:

Другой способ открыть файл — запустить редактор и ввести :e file_name , где file_name — это имя файла, который вы хотите открыть.

Сохраните файл в Vim / Vi

Команда для сохранения файла в Vim :w .

Чтобы сохранить файл без выхода из редактора, вернитесь в нормальный режим, нажав Esc , введите :w и нажмите Enter .

Также существует команда обновления :up , которая записывает буфер в файл только при наличии несохраненных изменений.

Чтобы сохранить файл под другим именем, введите :w new_filename и нажмите Enter .

Сохраните файл и выйдите из Vim / Vi

Команда для сохранения файла в Vim и выхода из редактора :wq .

Чтобы сохранить файл и одновременно выйти из редактора, нажмите Esc чтобы переключиться в нормальный режим, введите :wq и нажмите Enter .

Другая команда для сохранения файла и выхода из Vim 😡 .

Разница между этими двумя командами заключается в том, что 😡 записывает буфер в файл, только если есть несохраненные изменения, тогда как :wq всегда записывает буфер в файл и обновляет время модификации файла.

Закройте Vim / Vi без сохранения файла

Чтобы выйти из редактора, не сохраняя изменений, переключитесь в нормальный режим, нажав Esc , введите :q! и нажмите Enter .

Выводы

В этом руководстве мы показали вам, как сохранить файл в Vim и выйти из редактора. Если вы новичок в Vim, посетите сайт Open Vim, где вы можете попрактиковаться в Vim с помощью интерактивного руководства.

Не стесняйтесь оставлять комментарии, если у вас есть вопросы.

Источник

How to Save a File in Vi / Vim Editor in Linux

It is true that learning Vi/Vim editor – a well-known text editor in the Linux ecosystem, is not as easy as learning Nano or Emacs, as it requires a little effort which is worthwhile.

Many people are afraid of learning it, but seriously, for no important reasons. In this short article, intended for Vi/Vim text editor newbies, we’ll learn a few basic commands; how to save a file after writing or modifying its content.

Install Vim on Linux Systems

In most of today’s Linux distributions, Vi/Vim editor comes pre-installed, if not install the full version of Vim (Debian systems provide vim-tiny with fewer features), using the system package manager as shown:

$ sudo apt install vim [On Debian, Ubuntu and Mint] $ sudo yum install vim [On RHEL/CentOS/Fedora and Rocky Linux/AlmaLinux] $ sudo emerge -a app-editors/vim [On Gentoo Linux] $ sudo apk add vim [On Alpine Linux] $ sudo pacman -S vim [On Arch Linux] $ sudo zypper install vim [On OpenSUSE]

Note: To use Vim’s latest features, you do need to install Vim from the source.

Читайте также:  Watch for file linux

How to Create Files in Vi/Vim

To create or open a file using vi/vim, run the following command, which will create a new file or open an existing file for editing.

$ vim file.txt OR $ vi file.txt

Vi/Vim Edit Modes

The Vi/Vim editor comes with two modes: Command and Insert. In Command mode you can use keyboard keys to copy, paste, delete, navigate, and do a number of various tasks except entering text.

In Insert mode, you can write text to file, use the Enter key to go to a new line, and use the arrow keys to navigate between text. To get into Insert mode, press i and start entering text as shown.

Press

How to Save Files in Vi/Vim Editor

Once you have modified a file, press [Esc] shift to the Command mode and press :w (save and continue editing) and hit [Enter] as shown below.

Save File in Vim

To save the file and exit at the same time, you can use the ESC and 😡 keys and hit [Enter] . Optionally, press [Esc] and type Shift + Z Z to save and exit the file.

Save and Exit File in Vim

Save Vim File Content to New File

To save the file content to a new file named newname, use ESC and :w newname or 😡 newname and hit [Enter] .

Save Vim Content to New File

From here, you can now move over to learn common Vi/Vim tips and tricks, understand the different modes and so much more:

Vi/Vim Keyboard Shortcuts

To understand more about the vi/vim editor, you need to create a new file and try learning yourself using the following common vi/vim keyboard shortcuts.

Vim Cheat Sheet

That’s it! In an upcoming article, we’ll show you how to exit the Vim text editor with simple commands. Remember to drop your comments via the feedback form below.

Источник

How to Save a File in Vi / Vim & Exit

Vim (Vi IMproved) is an open-source text editor for Unix and Linux systems. It is a powerful and stable tool for editing and writing text, both in the command-line interface and as an independent application in a GUI.

Take the first step in learning Vim with the basic save and exit commands. Follow this guide and learn how to save a file in Vi/Vim and exit the editor.

linux Tutorial on how to save a File in Vi / Vim text editor

  • A system running Linux.
  • A user with sudo privileges.
  • Access to a terminal/command line.
  • Vim installed (alternatively, use the default Vi).
Читайте также:  Установить firefox linux tar bz2

Using Vim Modes

When Vim launches, files are opened in command mode by default. This means that you can move around and edit the file, but cannot insert new text.

All alphanumeric keys in this mode are equal to commands, and pressing them will not display their value on the screen. For example, pressing the letter w will move the cursor one word forward.

To type text, you must be in insert mode. To switch to insert mode, press the i key. Now you can type text into a file.

To switch back to command mode, press the Esc button.

How to Save Changes in Vim

Vim offers different commands to save changes to a file, depending on whether you need to exit the text editor or not. Below are examples demonstrating how to save and exit, save without exiting, and exit without saving.

Start by opening a new text file using Vim:

Next, press i to enter insert mode and add some text.

Vim Save and Quit Command

To save a file and exit Vim, do the following:

1. Switch to command mode by pressing the Esc key.

2. Press : (colon) to open the prompt bar in the bottom left corner of the window.

3. Type x after the colon and hit Enter. This will save the changes and exit.

Vim Save And Quit The Editor Command

Alternatively, a command that will also save a file and exit the text editor is:

In which case the w stands for write (save) and q stands for quit.

How to Save a File in Vi / Vim Without Exiting

To save a file without exiting in Vim:

1. Switch to command mode by pressing the Esc key.

2. Type : (colon). This will open the prompt bar in the bottom left corner of the window.

example of saving a file without exiting in Vim

3. Type w after the colon and hit Enter. This will save in Vim the changes made to the file, without exiting.

You can also rename an existing file by adding the new name after the commands.

In the picture below, we renamed the existing example1.txt into newexample.

example of renaming a file using vi/vim text editor

Exit Without Saving Changes in Vi / Vim

To exit Vim without saving changes:

1. Switch to command mode by pressing the Esc key.

2. Press : (colon) to open the prompt bar in the bottom left corner of the window.

3. Type q! after the colon and hit Enter to exit without saving the changes.

command to exit vim without saving changes

The q! quits the text editor.

This article explained how to save files in Vi / Vim, with multiple command options.

The more comfortable you feel using keyboard shortcuts, the more you will understand why Vim earned its worldwide reputation. Next learn how to copy and paste in Vim, and how to go to the end of the file!

Источник

Оцените статью
Adblock
detector