快捷教程：如何在命令行上编辑文件
编辑器
![](/data/attachment/album/201803/29/125951j1hzg8sd36hosws4.jpg)


此次教程中，我们将向您展示三种命令行编辑文件的方式。本文一共覆盖了三种命令行编辑器，vi（或 vim）、nano 和 emacs。


### 在命令行上使用 Vi 或 Vim 编辑文件


您可以使用 `vi` 编辑文件。运行如下命令，打开文件：



```
vi /path/to/file

```

现在，您可以看见文件中的内容了（如果文件存在。请注意，如果此文件不存在，该命令会创建文件）。


`vi` 最重要的命令莫过于此：


键入 `i` 进入<ruby> 编辑 <rt>  Insert </rt></ruby>模式。如此，您可以编辑文本。


退出编辑模式请键入 `ESC`。


正处于光标之下的字符，使用 `x` 键删除（您千万不要在编辑模式这样做，如果您这样做了，将不会删除光标下的字符，而是会在光标下插入 `x` 字符）。因此，当您仅仅使用 `vi` 打开文本（LCTT 译注：此时默认进入指令模式），此时您可以使用 `x` 键立即删除字符。在编辑模式下，您需要键入 `ESC` 退出编辑模式。


如果您做了修改，想要保存文件，请键入 `:x`（同样，您不能在编辑模式执行此操作。请按 `ESC` 退出编辑模式，完成此操作）。


如果您并没有做修改，键入 `:q` 退出文本（您同样不能在编辑模式执行此操作）。


如果您做了修改，但却想不保存文本而之际退出，请键入 `:q!` （同样不能在编辑模式执行此作）。


请注意在上述所有操作中，您都可以使用方向键操控光标在文本中的位置。


以上所有都是 `vi` 编辑器的内容。请注意，`vim` 编辑器或多或少也会支持这些操作，如果您想深层次了解 `vim`，请看 [这里](https://www.howtoforge.com/vim-basics)。


### 使用 Nano 命令行编辑器编辑文件


接下来是 Nano 编辑器。您可以执行 `nano` 命令调用它：



```
nano

```

这里是 `nano` 的用户界面：


![Nano 命令行编辑器](/data/attachment/album/201803/29/125956w2cosbvuahxlvdvb.png)


您同样可以使用它启动文件。



```
nano [filename]

```

例如：



```
nano test.txt

```

![在 nano 中打开文件](/data/attachment/album/201803/29/125957jux9prajr4fiaffr.png)


如您所见的用户界面，大致被分成四个部分。编辑器顶部显示编辑器版本、正在编辑的文件和编辑状态。然后是实际编辑区域，在这里，您能看见文件的内容。编辑器下方高亮区展示着重要的信息，最后两行显示能执行基础任务地快捷键，切实地帮助初学者。


这里是您前期应当了解的快捷键快表。


使用方向键浏览文本，退格键删除文本，`Ctrl+O` 保存文件修改。当您尝试保存时，`nano` 会征询您的确认（请参阅截图中主编辑器下方区域）：


![在 nano 中保存文件](/data/attachment/album/201803/29/125959galu5oo3jvuf24lu.png)


注意，在这个阶段，您有一个选项，可以保存不同的系统格式。键入 `Alt+D` 选择 DOS 格式，`Atl+M` 选择 Mac 格式。


![以 DOS 格式保存文件](/data/attachment/album/201803/29/130000zaowbhv55ocb5c5a.png)


敲回车保存更改。


![文件已经被保存](/data/attachment/album/201803/29/130001nzggxzbcbnwx0nbx.png)


继续，文本剪切使用 `Ctrl+K`，文本复制使用 `Ctrl+U`。这些快捷键同样可以用来粘贴剪切单个单词，但您需要先选择好单词，通常，您可以通过键入 `Alt+A`（光标在第一个单词下） 然后使用方向键选择完整的单词。


现在来进行搜索操作。使用 `Ctrl+W` 可以执行一个简单的搜索，同时搜索和替换您可以使用 `Ctrl+\\`。


![使用 nano 在文件中搜索](/data/attachment/album/201803/29/130002i6fa33k25u9um906.png)


这些就是 `nano` 的一些基础功，它能给您带来一些不错的开始，如果您是初次使用 `nano` 编辑器。更多内容，请阅读我们的完整内容，点击 [这里](https://www.howtoforge.com/linux-nano-command/)。


### 使用 Emacs 命令行编辑器编辑文件


接下来登场的是 Emacs。如果系统未安装此软件，您可以使用下面的命令在您的系统中安装它：



```
sudo apt-get install emacs

```

和 `nano` 一致，您可以使用下面的方式在 `emacs` 中直接打开文件：



```
emacs -nw [filename]

```

注意：`-nw` 选项确保 `emacs` 在本窗口启动，而不是打开一个新窗口，默认情况下，它会打开一个新窗口。


一个实例：



```
emacs -nw test.txt

```

下面是编辑器的用户界面：


![在 emacs 中打开文件](/data/attachment/album/201803/29/130003jm6mri6xvjmsq666.png)


和 `nano` 一样，`emacs` 的界面同样被分割成了几个部分。第一部分是最上方的菜单区域，和您在图形界面下的应用程序一致。接下来是显示文本（您打开的文件文本）内容的主编辑区域。


编辑区域下方坐落着另一个高亮菜单条，显示了文件名，编辑模式（如截图内的 ‘Text’）和状态（`**` 为已修改，`-` 为未修改，`%%` 为只读）。最后是提供输入指令的区域，同时也能查看输出。


现在开始基础操作，当您做了修改、想要保存时，在 `Ctrl+x` 之后键入 `Ctrl+s`。最后，在面板最后一行会向您显示一些信息：‘Wrote ........’。这里有一个例子：


![emascs 中保存文件](/data/attachment/album/201803/29/130005mvsvzd5x5fxa3srz.png)


现在，如果您放弃修改并且退出时，在 `Ctrl+x` 之后键入`Ctrl+c`。编辑器将会立即询问，如下图：


![emacs 中抛弃修改](/data/attachment/album/201803/29/130007tmlwz22qq2ywx38p.png)


输入 `n` 之后键入 `yes`，之后编辑器将会不保存而直接退出。


请注意，Emacs 中 `C` 代表 `Ctrl`，`M` 代表 `Alt`。比如，当你看见 `C-x`，这意味着按下 `Ctrl+x`。


至于其他基本编辑器操作，以删除为例，大多数人都会，使用 `Backspace`/`Delete` 键。然而，这里的一些删除快捷键能够提高用户体验。比如，使用 `Ctrl+k` 删除一整行，`Alt+d` 删除一个单词，`Alt+k` 删除一个整句。


在键入 `Ctrl+k` 之后键入 `u` 将撤销操作，输入 `Ctrl+g` 之后输入 `Ctrl+_` 恢复撤销的操作。使用 `Ctrl+s` 向前搜索，`Ctrl+r` 反向搜索。


![使用 emacs 在文件中搜索](/data/attachment/album/201803/29/130008kq9mmiiroh3i5vo8.png)


继续，使用 `Alt+Shift+%` 执行替换操作。您将被询问要替换单词。回复并回车。之后编辑器将会询问您是否替换。例如，下方截图展示了 `emacs` 询问使用者关于单词 ‘This’ 的替换操作。


![使用 emacs 替换单词](/data/attachment/album/201803/29/130009igxu9g994xmn1d12.png)


输入替换文本并回车。每一个替换操作 `emacs` 都会等待询问，下面是首次询问：


![确定文本替换](/data/attachment/album/201803/29/130010fozfz11kcoktt8fq.png)


键入 `y` 之后，单词将会被替换。


![键入 y 确定操作](/data/attachment/album/201803/29/130011i3u7p87l45llzcvm.png)


这些就是几乎所有的基础操作，您在开始使用 `emacs` 时需要了解掌握的。对了，我们忘记讨论如何访问顶部菜单，其实这些可以通过使用 `F10` 访问它们。


![基础编辑器操作](/data/attachment/album/201803/29/130012gqfd9mxmnddsgd9u.png)


按 `Esc` 键三次，退出这些菜单。




---


via: <https://www.howtoforge.com/faq/how-to-edit-files-on-the-command-line>


作者：[Falko Timme, Himanshu Arora](https://www.howtoforge.com) 译者：[CYLeft](https://github.com/CYLeft) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
# How do I edit files on the command line?

**Authors:** Falko Timme, Himanshu Arora, Till Brehm

In this tutorial, we will show you how to edit files on the command line. This article covers three command-line editors, vi (or vim), nano, and emacs. These editors are available on all Linux distributions like Arch Linux, CentOS, Debian, Fedora, and Ubuntu.

## Editing Files with Vi or Vim Command Line Editor

To edit files on the command line, you can use an editor such as vi. To open the file, run

vi /path/to/file

Now you see the contents of the file (if there is any. Please note that the file is created if it does not exist yet.).

As an example. I opened the /etc/passwd file with vi:

The most important commands in vi are these:

Press i to enter the Insert mode. Now you can type in your text.

To leave the Insert mode press ESC.

To delete the character that is currently under the cursor you must press x (and you must not be in Insert mode because if you are you will insert the character x instead of deleting the character under the cursor). So if you have just opened the file with vi, you can immediately use x to delete characters. If you are in Insert mode you have to leave it first with ESC.

If you have made changes and want to save the file, press :x (again you must not be in Insert mode. If you are, press ESC to leave it).

If you haven't made any changes, press :q to leave the file (but you must not be in Insert mode).

If you have made changes, but want to leave the file without saving the changes, press :q! (but you must not be in Insert mode).

Please note that during all these operations you can use your keyboard's arrow keys to navigate the cursor through the text.

So that was all about the vi editor. Please note that the vim editor also works more or less in the same way, although if you'd like to know vim in depth, head [here](https://www.howtoforge.com/vim-basics).

## Editing Files with Nano Command Line Editor

Next up is the Nano editor. You can invoke it simply by running the 'nano' command:

nano

Here's how the nano UI looks like:

You can also launch the editor directly with a file.

nano [filename]

For example:

nano test.txt

The UI, as you can see, is broadly divided into four parts. The line at the top shows editor version, the file being edited, and the editing status. Then comes the actual edit area where you'll see the contents of the file. The highlighted line below the edit area shows important messages, and the last two lines are really helpful for beginners as they show keyboard shortcuts that you use to perform basic tasks in nano.

So here's a quick list of some of the shortcuts that you should know upfront.

Use arrow keys to navigate the text, the Backspace key to delete text, and **Ctrl+o** to save the changes you make. When you try saving the changes, nano will ask you for confirmation (see the line below the main editor area in screenshot below):

Note that at this stage, you also have an option to save in different OS formats. Pressing **Altd+d** enables the DOS format, while **Atl+m** enables the Mac format.

Press enter and your changes will be saved.

Moving on, to cut and paste lines of text use **Ctrl+k** and **Ctrl+u**. These keyboard shortcuts can also be used to cut and paste individual words, but you'll have to select the words first, something you can do by pressing **Alt+A** (with the cursor under the first character of the word) and then using the arrow to key select the complete word.

Now comes search operations. A simple search can be initiated using **Ctrl+w**, while a search and replace operation can be done using **Ctrl+\**.

So those were some of the basic features of nano that should give you a head start if you're new to the editor. For more details, read our comprehensive coverage [here](https://www.howtoforge.com/linux-nano-command/).

## Editing Files with Emacs Command Line Editor

Next comes **Emacs**. If not already, you can install the editor on your system using the following command:

sudo apt-get install emacs

Like nano, you can directly open a file to edit in emacs in the following way:

emacs -nw [filename]

**Note**: The **-nw** flag makes sure emacs launches in bash itself, instead of a separate window which is the default behavior.

For example:

`emacs -nw test.txt`


Here's the editor's UI:

Like nano, the emacs UI is also divided into several parts. The first part is the top menu area, which is similar to the one you'd see in graphical applications. Then comes the main edit area, where the text (of the file you've opened) is displayed.

Below the edit area sits another highlighted bar that shows things like name of the file, editing mode ('Text' in screenshot above), and status (** for modified, - for non-modified, and %% for read only). Then comes the final area where you provide input instructions, see output as well.

Now coming to basic operations, after making changes, if you want to save them, use **Ctrl+x** followed by **Ctrl+s**. The last section will show you a message saying something on the lines of '**Wrote ........' . **Here's an example:

Now, if you want to discard changes and quit the editor, use **Ctrl+x** followed by **Ctrl+c**. The editor will confirm this through a prompt - see screenshot below:

Type 'n' followed by a 'yes' and the editor will quit without saving the changes.

*Please note that Emacs represents 'Ctrl' as 'C' and 'Alt' as 'M'. So, for example, whenever you see something like C-x, it means Ctrl+x.*

As for other basic editing operations, deleting is simple, as it works through the Backspace/Delete keys that most of us are already used to. However, there are shortcuts that make your deleting experience smooth. For example, use **Ctrl+k** for deleting complete line, **Alt+d** for deleting a word, and **Alt+k** for a sentence.

Undoing is achieved through '**Ctrl+x**' followed by '**u**', and to re-do, press **Ctrl+g** followed by **Ctrl+_**. Use **Ctrl+s** for forward search and **Ctrl+r** for reverse search.

Moving on, to launch a replace operation, use the Alt+Shift+% keyboard shortcut. You'll be asked for the word you want to replace. Enter it. Then the editor will ask you for the replacement. For example, the following screenshot shows emacs asking user about the replacement for the word 'This'.

Input the replacement text and press Enter. For each replacement operation emacs will carry, it'll seek your permission first:

Press 'y' and the word will be replaced.

So that's pretty much all the basic editing operations that you should know to start using emacs. Oh, and yes, those menus at the top - we haven't discussed how to access them. Well, those can be accessed using the F10 key.

To come out of these menus, press the Esc key three times.