用vi编辑文件
原文:https://www.ibm.com/developerworks/library/l-lpic1-103-8/index.html
Overview
In this article, learn the basic use of the vi editor, which is almost always available on any Linux or UNIX system. Learn to:
- Navigate a document using vi
- Use basic vi modes
- Insert, edit, delete, copy, and find text
This article helps you prepare for Objective 103.8 in Topic 103 of the Linux Professional Institute's Junior Level Administration (LPIC-1) exam 101. The objective has a weight of 3.
Prerequisites
To get the most from the articles in this series, you should have a basic knowledge of Linux and a working Linux system on which you can practice the commands covered in this article. Sometimes different versions of a program will format output differently, so your results may not always look exactly like the listings and figures shown here.
Navigating documents with vi
Connect with Ian
Ian is one of our most popular and prolific authors. Browse all of Ian's articles on developerWorks. Check out Ian's profile and connect with him, other authors, and fellow readers in My developerWorks.
The vi editor is almost certainly on every Linux and UNIX system. In fact, if a system has just one editor, it's probably vi, so it's worth knowing your way around in vi. This article introduces you to some basic vi editing commands, but for a full vi tutorial, check out our tutorial on vi "vi intro -- the cheat sheet method", or consult the man pages or one of the many excellent books that are available.
Starting vi
Develop skills on this topic
This content is part of a progressive knowledge path for advancing your skills. See Basics of Linux system administration: Working at the console
Most Linux distributions now ship with the vim (for Vi IMproved) editor rather than classic vi. Vim is upward compatible with vi and has a graphical mode available (gvim) as well as the standard vi text mode interface. The vi
command is usually an alias or symbolic link to the vim program. There are several versions of vim: tiny, small, normal, big, and huge. You can find out what version of vim you are running and what features are included by using the command:
1
|
vi --version |
If you recall the section on changing priorities in a previous article "Learn Linux, 101: Process execution priorities," we wanted to change the priority of our running count1.sh shell script. Perhaps you tried this yourself and found that the command ran so fast that you didn't have enough time to accomplish the priority change with renice
. So let's start by using the vi editor to add a line at the beginning of the file to sleep for 20 seconds so we have some time to change priorities.
About this series
This series of articles helps you learn Linux system administration tasks. You can also use the material in these articles to prepare for Linux Professional Institute Certification level 1 (LPIC-1) exams.
See our series roadmap for a description of and link to each article in this series. The roadmap is in progress and reflects the latest (April 2009) objectives for the LPIC-1 exams: as we complete articles, we add them to the roadmap. In the meantime, though, you can find earlier versions of similar material, supporting previous LPIC-1 objectives prior to April 2009, in our LPI certification exam prep tutorials.
If you don't still have the count1.sh program around, open a terminal window in your home directory and paste in the commands from Listing 1. This will create count1.sh in a directory called lpi103-8 and place you in that directory.
Listing 1. CPU-intensive script - count1.sh
1
2
|
mkdir -p lpi103-8 && cd lpi103-8 && {echo 'x="$1"'>count1.shecho 'echo "$2" $(date)'>>count1.shecho 'while [ $x -gt 0 ]; do x=$(( x-1 ));done'>>count1.shecho 'echo "$2" $(date)'>>count1.sh } |
To edit an existing file, use the vi
command with a filename as a parameter. See the man pages orRelated topics for details on the many options that are available. For now, just use the command without options:vi count1.sh
This should open the count1.sh file. You should see a display similar to Listing 2. If you are using vim, some of the words or characters may be in color. Vim has a syntax highlighting mode (which was not part of the original vi editor), and it may be turned on by default on your system.
Listing 2. Editing count1.sh using vi
1
2
3
4
5
6
7
8
9
|
x="$1" echo "$2" $(date) while [ $x -gt 0 ]; do x=$(( x-1 ));done echo "$2" $(date) ~ ~ ~ ~ "count1.sh" 4L, 84C 1,1 All |
The vi editor dates from the time when not all terminal keyboards had cursor movement keys, so everything you can do in vi can be done with the keys typically found on a standard typewriter plus a couple of keys such as Esc and Insert. However, you can configure vi to use additional keys if they are available; most of the keys on your keyboard do something useful in vi. Because of this legacy and the slow nature of early terminal connections, vi has a well-deserved reputation for using very brief and cryptic commands. Let's start by looking at the keystrokes for navigation around your file.
Moving around
These commands help you move around in a file:
- h
- Move left one character on the current line
- j
- Move down to the next line
- k
- Move up to the previous line
- l
- Move right one character on the current line
- w
- Move to the next word on the current line
- e
- Move to the next end of word on the current line
- b
- Move to the previous beginning of the word on the current line
- Ctrl-f
- Scroll forward one page
- Ctrl-b
- Scroll backward one page
If you type a number before any of these commands, then the command will be executed that many times. This number is called a repetition count or simply count. For example, 5h will move left five characters. You can use repetition counts with many vi commands.
Moving to lines
The following commands help you move to specific lines in your file:
- G
- Moves to a specific line in your file. For example, 3G moves to line 3. With no parameter, G moves to the last line of the file.
- H
- Moves relative to the top line on the screen. For example, 3H moves to the line currently 3rd from the top of your screen.
- L
- Is like H, except that movement is relative to the last line on screen. Thus, 2L moves to the second-to-last line on your screen.
Practice these commands until you are comfortable moving around the file. If you get stuck and things aren't working as expected, read on and learn how to get out of the file.
Getting out of vi
One of the most useful things to know about a new editor is how to get out of it before you do anything you shouldn't do, such as destroying an important configuration file. You can get out of vi by saving or abandoning your changes, or by restarting from the beginning. If these commands don't seem to work for you, you may be in insert mode, which you will learn about in a moment. If in doubt, pressing Esc will leave insert mode and return you to command mode where these commands should work.
- :q!
- Quit editing the file and abandon all changes. This is a very common idiom for getting out of trouble.
- :w!
- Write the file (whether modified or not). Attempt to overwrite existing files or read-only or other unwritable files. You may give a filename as a parameter, and that file will be written instead of the one your started with. It's generally safer to omit the ! unless you know what you're doing here.
- ZZ
- Write the file if it has been modified. Then exit. This is a very common idiom for normal vi exit.
- :e!
- Edit the current disk copy of the file. This will reload the file, abandoning changes you have made. You may also use this if the disk copy has changed for some other reason and you want the latest version.
- :!
- Run a shell command. Type the command and press Enter. When the command completes, you will see the output and a prompt to return to vi editing.
Notes:
- When you type the colon (:), your cursor will move to the bottom line of your screen where you can type in the command and any parameters.
- If you omit the exclamation point from the above commands, you may receive an error message such as one saying changes have not been saved, or the output file cannot be written (for example, you are editing a read-only file).
- The : commands have longer forms (:quit, :write, :edit), but the longer forms are seldom used.
vi modes
The vi editor has two modes of operation:
- Command mode
- In command mode, you move around the file and perform editing operations such as searching for text, deleting text, changing text, and so on. You usually start in command mode.
- Insert mode
- In insert mode, you type new text into the file at the insertion point. To return to command mode, press the Esc (Escape) key.
These two modes determine the way the editor behaves. Anything you type in insert mode is considered text to be inserted into the file. If you are trying to type a command and nothing happens, or the character appears under the cursor, then you probably forgot to press Esc to escape from insert mode.
Editing text
Now that you can open a file in vi, move around it and get out, it's time to learn how to edit the text in the file.
Modifying text
Use the following commands when you need to insert, delete, or modify text. Note that some of these commands have an uppercase form that is similar to the lowercase form; see the descriptions below.
- i
- Enter insert mode before the character at the current position. Type your text and press Esc to return to command mode. Use I to insert at the beginning of the current line.
- a
- Enter insert mode after the character at the current position. Type your text and press Esc to return to command mode. Use A to insert at the end of the current line.
- c
- Use c to change the current character and enter insert mode to type replacement characters.
- o
- Open a new line for text insertion below the current line. Use O to open a line above the current line.
- cw
- Delete the remainder of the current word and enter insert mode to replace it. Use a repetition count to replace multiple words. Use c$ to replace to end of line.
- dw
- Same as for cw (and c$) above, except that insert mode is not entered.
- dd
- Delete the current line. Use a repetition count to delete multiple lines.
- x
- Delete the character at the cursor position. Use a repetition count to delete multiple characters.
- p
- Put the last deleted text after the current character. Use P to put it before the current character.
- xp
- This combination of x and p is a useful idiom. This swaps the character at the cursor position with the one on its right.
Searching text
You can search for text in your file using regular expressions:
- /
- Use / followed by a regular expression to search forward in your file.
- ?
- Use ? followed by a regular expression to search backward in your file.
- n
- Use n to repeat the last search in either direction.
You may precede any of the above search commands with a number indicating a repetition count. So 3/x will find the third occurrence of x from the current point, as will /x followed by 2n. Similarly, 2/^e will find the second line from the current position that starts with e.
Note that search will wrap around to the top once the bottom of file is reached.
Getting help
Another useful command in vi is the help command, which you invoke by typing :help
. Help will open inside vi; use the :q
command to leave help and go back to your work. If you want help on some particular topic, say wrapping of lines, try adding a word after the :help command, for example: :help wrap
.
Putting it together
We began by wanting to add a line to our count1.sh file. To keep the original and save the modified version as count2.sh, we could use these vi commands once we open the file with vi
. Note that <Esc> means to press the Esc key.
Listing 3. Editor commands to add a line to count1.sh
1
|
1GOsleep 20< Esc > :w! count2.sh :q |
These commands do the following:
- 1G
- Move to the first line of the file
- O
- Open a new line above it and enter insert mode
- sleep 20
- The new text that you want to add
- <Esc>
- Press the Esc key to return to command mode
- :w! count2.sh
- Write the file to disk
- :q
- Close vi
Simple when you know how.
This is the last article for Exam 101 - Topic 103: GNU and UNIX commands. See our series roadmapfor a description of and link to other articles in this series.
Downloadable resources
用vi编辑文件的更多相关文章
- CentOS7--Xshell网络中断引起的vi编辑文件问题
在编写Python的程序时,由于不小心触碰网线使xshell出现网络中断问题,当再次以vi命令打开文件准备编辑时,发现爆出英文错误: 该错误的英文翻译大概是(1)另一个程序也在编译这个文件,如果是这样 ...
- ubuntu下使用VI编辑文件必知的常用命令
进入vi的命令 vi filename :打开或新建文件,并将光标置于第一行首 vi +n filename :打开文件,并将光标置于第n行首 vi + filename :打开文件,并将光标置于最后 ...
- vi编辑文件保存后,提示“Can't open file for writing Press ENTER or type command to continue”
在linux上使用vi命令修改或者编辑一个文件内容的时候,最后发现使用<Esc+:+wq!>无法保存退出,却出现,如下提示: E212: Can't open file for writi ...
- Linux上vi编辑文件非正常退出后文件恢复
Vim另存文件的命令为 编辑完文件后Esc,输入以下指令 :w filename 编辑文件时非正常退出,会生成.hello.txt.swp的文件,还有一些其他信息 恢复文件要使用以下命令: [keys ...
- linux下vi编辑文件
vi 文件名.进入读文件模式 按i进入编辑模式 按g切光标换到第一行,按G光标切换到最后一行. 按Esc退出编辑模式 :q退出 :wq保存退出 以上命名后面加上!表示强制运行
- vi编辑文件出现Can't open file for writing错误
可以用 ll 命令查看一下文件的权限,很有可能是没有权限,用chmod命令修改一下权限就可以了(当然是文件所有者或者root用户才能修改),或者切换成root用户(不推荐)
- vi编辑文件E437: terminal capability "cm" required 解决办法
E437: terminal capability "cm" required 这个错误一般是环境变量TERM没有配置或者配置错误所致. 解决办法: 执行export TERM=x ...
- vi编辑时出现E325:ATTENTION
我们用vi编辑文件时,系统会提示E325:ATTENTION. 这是由于在编辑该文件的时候异常退出了,因为vi在编辑文件时会创建一个交换文件swap file以保证文件的安全性. 但是每次打开文件时都 ...
- linux vi/vim编辑文件显示行号
方法一(最尴尬的方法): 1.显示当前行行号,在VI的命令模式下输入 :nu 2.显示所有行号,在VI的命令模式下输入 :set nu #这是:set number 的简写 方法二(最好的方法): 使 ...
随机推荐
- 【SVN】CentOS7.0下搭建SVN服务器
SVN服务器搭建 最近接手了天赋吉运的SVN项目管理,那么学会搭建SVN服务器就成为了必须的技能.这篇文章就来讲一讲在CentOS7.0下如何搭建SVN服务器 1,下载安装SVN版本 yum inst ...
- 数字图像处理的Matlab实现(4)—灰度变换与空间滤波
第3章 灰度变换与空间滤波(2) 3.3 直方图处理与函数绘图 基于从图像亮度直方图中提取的信息的亮度变换函数,在诸如增强.压缩.分割.描述等方面的图像处理中扮演着基础性的角色.本节的重点在于获取.绘 ...
- 题解-POI2014 FAR-FarmCraft
Problem bzoj权限题,洛谷上可提交 洛谷上的奇葩翻译不要看,很多条件缺漏 题意简述:给定一棵树,每条边权为1,给定所有点点权,每条边仅能走两次,求以一定顺序遍历整棵树后,使所有点中的到达时间 ...
- $Django importlib与dir知识,手写配置文件, 配置查找顺序 drf分页器&drf版本控制
1 importlib与dir知识 # importlib简介动态导入字符串模块 # 常规导入 from ss.aa import b from ss import a print(b,type(b ...
- Android设备管理器——DevicePolicyManager
自从安卓2.2(API=8)以后,安卓手机是通过设备管理API对手机进行系统级的设备管理. 本篇通过大家熟悉的"一键锁屏"的小项目实现来介绍设备管理API如何通过强制设备管理策略创 ...
- HDU 1250
简单大数 (要压位,不然会超内存) #include<iostream> #include<cstdio> #include<cstring> #include&l ...
- Laravel 5.2--git冲突error: Your local changes to the following files would be overwritten by merge:
今天在服务器上git pull是出现以下错误: error: Your local changes to the following files would be overwritten by mer ...
- Spring 邮件发送
前言:以前都是直接用Java自带的邮件工具发送邮件,现在Spring帮我们做了封装,提供了更好用更简单的发送邮件工具JavaMailSender 关于邮件服务器的设置就不在这里说了,直接去QQ邮箱 ...
- windows下安装Rabbitmq详解
RabbitMQ是建立在强大的Erlang OTP平台上,因此安装Rabbit MQ的前提是安装Erlang. 1.什么是Erlang? Erlang(['ə:læŋ])是一种通用的面向并发的编程语言 ...
- Codeforces 1110D Jongmah [DP]
洛谷 Codeforces 我-我我把这-这这题切了??? 说实话这题的确不难,只是我看到有大佬没做出来有点慌-- 突然发现这题是我在洛谷的第500个AC呢.那就更要写篇题解纪念一下了. 思路 容易想 ...