10 cool VI command skills you must master

Source: Internet
Author: User
Tags first string switch case

Abstract: most Linux developers are quite familiar with vi, but unfortunately, most developers can only master some of the most common Linux vi commands, although many of the 10 vi commands described below are unknown, they can greatly improve your efficiency in practical applications.

When using the vi Editor-whether it's a first-time user or experienced user-most people tend to only master the Core Command set and these commands can execute the most common functions: navigate or save the file; insert, update, delete, or search for data; exit but do not save the modification.

However, the vi editor is extremely powerful with rich features and functions. Even after using vi for years, you may still find new unknown commands. The commands discussed in this article are not very well-known commands, but they can simplify your current operation methods and make your work more efficient, or, you can perform operations that you did not know you could do with vi.

Open and Close row numbers

Many options in the vi editor can control the appearance and feeling of editing sessions. Use the: set command to modify the session settings in vi. After you press the Escape key to enter the command mode, you can use the: set all command to display the list of options and settings. One of the options that can be set is number, which enables and disables row numbers.

#

# Internet host table

#

::1 localhost

127.0.0.1 localhost loghost

192.168.0.6 CentOS5

192.168.0.10 appserv

192.168.0.11 webserv

192.168.0.12 test

192.168.0.5 solaris10 # Added by DHCP

~

~

~

:set number

This vi command displays the row number on each record in the current edited file. After enabling vi to enter the command mode, you can enter: set number and press enter to open the line number.

#

# Internet host table

#

::1 localhost

127.0.0.1 localhost loghost

192.168.0.6 centos5

192.168.0.10 appserv

192.168.0.11 webserv

192.168.0.12 test

192.168.0.5 solaris10 # Added by DHCP

You can use the: set nonumber command to close the row number. You can also use this command and the abbreviation of: set number, that is, set nu and: set nonu. To quickly calculate the number of rows to be processed using the vi function, it is very helpful to display the row number. The row number is particularly useful when there are many rows that may span multiple screens. In addition, sometimes you know the row range to be processed, but you need to find out the initial and end line numbers to be used in the vi command. If you want to display the row number each time you enter the vi Session, add the set number row to the. exrc file in the main directory.

Auto indent

Indentation is an important part of a style when writing code in some programming languages, ensuring better code readability. If necessary, you can set Automatic indent in the vi editor based on the style of the programming language. Use autoindent to enable or disable auto indent.

#!/bin/ksh

#

#

for file in /etc/*

do

if [[ -f ${file} ]] ; then

echo “${file} is a file”

 

~

~

~

~

~

:set autoindent

After that, if you enter spaces or tabs at the beginning of a line, the new line will be indented to the same position. In command mode, enter: set autoindent and press enter to enable auto indent. Determine the indent level by setting shiftwidth. For example, set shiftwidth = 4 sets each level of indentation to four spaces.

#!/bin/ksh

#

#

for file in /etc/*

do

if [[ -f ${file} ]] ; then

echo “${file} is a file”

elif [[ -d ${file} ]] ; then

echo “${file} is a directory”

fi

done

~

~

:set shiftwidth=4

In command mode, you can use the> command to add a level-1 indent to an existing line, and use the <command to reduce the level-1 indent. Add an integer before these commands to increase or decrease the level-1 indent for multiple lines. For example, if you place the cursor at the beginning of Line 4 in Listing 4 and enter the command mode, enter 5> to add a level of indentation for the following five rows.

#!/bin/ksh

#

#

for file in /etc/*

do

if [[ -f ${file} ]] ; then

echo “${file} is a file”

elif [[ -d ${file} ]] ; then

echo “${file} is a directory”

fi

done

~

~

You can use the: set noautoindent command to disable automatic indent. You can also use the short description of this command and the autoindent command, namely: set ai and: set noai. You can also use: set ai sw = 4 to open the indent and set the indent level in a command. If you want to enable automatic indent every time you start a vi Session and set the indent level to four spaces, add set ai sw = 4 lines to the. exrc file in the main directory.

Case Insensitive during search

As you know®In the search, the mode match is case sensitive. However, if you want vi to be case insensitive, you can use the: set ignorecase command. Use: set noignorecase case sensitive. You can also use abbreviations (: set ic and: set noic ). If you want to enable case-insensitive search every time you enter a vi Session, add the set ignorecase row to the. exrc file in the main directory.

Compound search

In vi, you can use the/command to search for strings. You must specify the pattern to be matched in the form of a literal string or regular expression. For example, to search for the word echo in a file, you only need to enter command mode, enter/echo, and press Enter. This command will find the first word in line 3rd of the file shown in Listing 6.

#!/bin/ksh

#

echo “Starting”

file=${1}

echo ${file}

if [[ ${file} = 1 ]] ; then

((file=${file}+1))

echo “Adding one gives ” \

${file}

fi

echo “Ending”

exit

You can use a simple regular expression to specify the rows that contain a word and have another word. For example, to find the first line that contains string echo, followed by zero or more characters, and followed by string file, use/echo. * file. In the file shown in Listing 6, this command will find the first word in line 6th.

However, this command is considered to be a match only when the two strings appear on the same line. You can specify a semicolon (;) separate the two search commands to perform a composite search. For example, to search for the string echo that appears after the string {file} + 1, use/{file} + 1/;/echo /. In the file shown in Listing 6, this command will find the first word in line 10th. Composite search is particularly useful for finding a command that appears after another command in the code-for example, where a function is called after a variable is set.

Replay Search Mode

When you search for a replacement pattern in a file, you can let vi save any pattern to be matched in the buffer; then, when performing the replacement, you can use the buffer reference number to replay them. The method is to place the mode between \ (and \), which instructs vi to place the mode in the numbered buffer (1 to 9. During replacement, you can use the buffer reference numbers \ 1 to \ 9 to reference These buffers.

For example, if you want to search for lines starting with the word Martin in the file shown in listing 7 and add the prefix Mr and the suffix Wicks to each match, enter the command mode and enter the vi command: % s/^ \ (Martin \)/Mr \ 1 Wicks/g, and press Enter.

Martin is an IT consultant. Martin likes

snowboarding and mountain biking. Martin has

worked on UNIX systems for over 15 years. Martin also

worked for many years before that on mainframes.

Martin lives in London.

~

~

~

~

:%s/^\(Martin\)/Mr \1 Wicks/g

The following is an explanation of this command:

: % S-Indicates vi to replace.

/-Mode separator.

^ \ (Martin \)-searches for the row starting with the string Martin and saves the string in buffer 1.

/-Mode separator.

Mr \ 1 Wicks-replace the string found with the string Mr, add the content in buffer 1, and add the string Wicks.

/-Mode separator.

G-Global modification (that is, modifying all matching locations)

Buffer references can be used in both search and replacement strings.

Mr Martin Wicks is an IT consultant. Martin likes

snowboarding and mountain biking. Martin has

worked on UNIX systems for over 15 years. Martin also

worked for many years before that on mainframes.

Mr Martin Wicks lives in London.

~

~

~

~

:%s/^\(Martin\)/Mr \1 Wicks/g

Bookmarks

Allows vi to add bookmarks to a specific position in the file. Press the Escape key, then press the M key, and then enter another alphabet character that represents the bookmarked reference. Therefore, you can have up to 26 bookmarks named a to z. To return to the previous bookmarks, press the Escape key, then press the reverse marker ('), and then enter the quote character of the bookmarks.

For example, if you press Escape and press the M and A keys, the current cursor position is saved in bookmarks. In the edit session, when you want to return to this cursor position, you only need to press Escape and then enter 'a. You can use the double anti-apostrophes (") command to switch between the current and previous bookmarks.

Search, update, find next, and duplicate

In the vi Editor, one of the most useful search/replacement features is to search for a string that matches a certain pattern, update it, and then continue searching for the next matched string, then, select whether to update it in the same way. This is similar to Microsoft®The next/replacement function in Word is similar. You may already know that you can search for the string mode in vi by entering the command mode, input/search_pattern (where search_pattern is a string or regular expression), and press Enter. In this way, the first string that matches the specified pattern is found. After that, you can perform any operations on the found text. For example, if you press Escape, then press the C and W keys, and then enter more text, the string will be replaced with another word.

To quickly find the next place that matches the pattern, press Escape and then press N. When finding the next match, you can use the dot (.) Key to repeat the most recent text operation at this position, such as the modify word (cw) operation used in the previous example. Then, you can use these keys to continue searching for other matches (n) and select repeated text operations (.). The operation method is similar to the search next/replace function in Word.

Switch case sensitivity

In vi, you can change the case sensitivity of letter Characters Under the cursor by pressing Escape and then pressing the Tilde (~). This will switch back and forth between lower case and upper case. Press this key to move the cursor to each character in the row, and the case of each letter to be switched. You can enter a number before the Tilde to indicate how many letter characters you want to change the case sensitivity.

Filter

As you may know, press Escape in vi and enter :! Command (the command is the UNIX command to be executed), and press enter to execute the command in shell. For example ,:! Pwd displays the current working directory of the editing session.

However, you can also send a part of the file as a standard input to the UNIX Command and replace the same part in the editing buffer with the generated output. For example, if you want to sort the entire file shown in listing 9 in a vi Session, you can press Escape and enter: 1, $! Sort and press Enter. This allows vi to pass all content from the first line to the end of the file ($) to the sort command and replace the specified part with the output.

In addition, you can add the number of rows to be operated starting from the current cursor position before the shell command. The method is to press Escape, enter the number of the specified number of rows, and then enter Two exclamation points (!!), Finally, enter the UNIX Command.

You can use the pipeline separator (|) to connect UNIX commands to perform complex and powerful filtering in a vi Session. For example, if you want to replace the file content in the editing buffer of the current vi session with the first space-separated field in each line, sort in ascending order and convert it to uppercase, after Pressing Escape, enter:

:1,$!awk ‘{print $1}’ | sort | tr [:lower:] [:upper:]

Save part of content

You can save part of the content of the currently edited file by pressing Escape and then input start and endw file. The start is the first line to be saved in the current file, end is the last row to be saved. w indicates that you want to write it to another file (or overwrite the existing file). file is the specified part of the file to be saved. For the last row, you can use $ to indicate the end of the file. You can use two greater signs (>) after w to indicate that you want to append the content to the file, rather than overwrite the file. The example in listing 12 attaches rows 6th to 9th (inclusive) to the file/tmp/newfile.

#

# Internet host table

#

::1 localhost

127.0.0.1 localhost loghost

192.168.0.6 centos5

192.168.0.10 appserv

192.168.0.11 webserv

192.168.0.12 test

192.168.0.5 solaris10 # Added by DHCP

~

~

~

:6,9w >> /tmp/newfile

Conclusion
The vi editor is an extremely powerful tool. This article provides some tips and tricks to help you edit files more efficiently. Remember that vi has more features that are not very well known. Have a good time!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.