Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the skills of using vi editor in linux

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the use of linux vi editor skills, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian with you to understand.

Open and close line number

There are many options in the vi editor that control the look and feel of the editing session. Use the: set command to modify the session settings in vi. After pressing Escape to enter command mode, you can use the: set all command to display a list of options and settings.

One of the options you can set is number, which turns line numbers on and off (see listing 1).

Listing 1. # # Internet host table#::1 localhost127.0.0.1 localhost loghost192.168.0.6 centos5192.168.0.10 appserv192.168.0.11 webserv192.168.0.12 test192.168.0.5 solaris10 # Added by DHCP~~~:set number before opening the line number

This command causes vi to display the line number on each record in the currently edited file. After putting vi into command mode, type: set number and press enter to open the line number (see listing 2).

Listing 2. After opening the line number, 1 # 2 # Internet host table3 # 4:: 1 localhost5 127.0.0.1 localhost loghost6 192.168.0.6 centos57 192.168.0.10 appserv8 192.168.0.11 webserv9 192.168.0.12 test10 192.168.0.5 solaris10 # Added by DHCP~~~:set number

You can turn off the line number using the: set nonumber command. You can also use the abbreviations of this command and the: set number command, namely: set nu and: set nonu.

Displaying line numbers can be very helpful if you need to quickly calculate the number of lines to be processed with the vi function. Line numbers are especially useful when there are a large number of lines that may span multiple screens. In addition, sometimes you know the range of lines to deal with, but you need to find out the initial and ending line numbers to use in the vi command.

If you want the line number to be displayed every time you enter a vi session, add the set number line to the .exrc file in the home directory.

Automatic indent

When writing code in some programming languages, indentation is an important part of the style to ensure that the code is more readable. If desired, you can indent automatically in the vi editor based on the style settings of the programming language. Use autoindent to turn automatic indentation on or off (see listing 3).

Listing 3. Open auto indent #! / bin/ksh##for file in/ etc/*doif [[- f ${file}]]; thenecho "${file} is a file" ~: set autoindent

After that, if you enter a space or tab at the beginning of a line, subsequent new lines will be indented to the same position. In command mode, type: set autoindent, and then press enter to turn on automatic indentation. Determine the indentation level by setting shiftwidth. For example, set shiftwidth=4 sets each level of indentation to four spaces (see listing 4).

Listing 4. Set indentation level #! / bin/ksh##for file in/ etc/*doif [[- f ${file}]]; thenecho "${file} is a file" elif [[- d ${file}]]; thenecho "${file} is a directory" fidone~~:set shiftwidth=4

In command mode, you can use the > > command to add one level of indentation to an existing line, and use (command to reduce one level of indentation. Add an integer to these commands to increase or decrease multiple lines by one level of indentation. For example, place the cursor at the beginning of line 6 in listing 4, and after entering command mode, type 5) to add one level of indentation to the following five lines. Listing 5 shows the results.

Listing 5. Indent code block #! / bin/ksh##for file in/ etc/*doif [[- f ${file}]]; thenecho "${file} is a file" elif [[- d ${file}]]; thenecho "${file} is a directory" fidone~~

You can use the: set noautoindent command to turn off automatic indentation. You can also use this command and the abbreviations of the autoindent command, namely: set ai and: set noai. You can also use: set ai sw=4 to turn on indentation in a command and set the indentation level.

If you want to enable automatic indentation and set the indentation level to four spaces each time you start a vi session, add the set ai sw=4 line to the .exrc file in the home directory.

Case-insensitive when searching

As you know, pattern matching is case-sensitive when performing a search in UNIX ®. However, if you want vi to be case-insensitive, you can use the: set ignorecase command. Use: set noignorecase to restore case sensitivity. 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 line to the .exrc file in your home directory.

Compound search

In vi, you can use the / command to search for a string, which requires specifying the pattern to match in the form of a literal string or regular expression. For example, to search for the word echo in a file, simply enter command mode, type / echo, and then press enter. This command will find the * * words on line 3 of the file shown in listing 6.

Listing 6. Compound search 1 #! / bin/ksh2 # 3 echo "Starting" 4 file=$ {1} 56 echo ${file} 78 if [[${file} = 1]]; then9 ((file=$ {file} + 1) 10 echo "Adding one gives"\ 11 ${file} 12 fi13 echo "Ending" 14 exit~~

You can use a simple regular expression to specify a line that contains a word followed by another word. For example, to find a * * line that contains the string echo, followed by zero or more characters, followed by the string file, you should use / echo.*file. In the file shown in listing 6, this command finds the * words on line 6.

However, this command is considered to match only if the two strings appear on the same line. If you want to search for a pattern or string that appears after another pattern or string, regardless of whether the two patterns or strings are on the same line, you can specify two search commands separated by a semicolon (;) to perform a compound search. For example, to search for the string echo that appears after the string {file} + 1, you should use / {file} + 1 match echo /. In the file shown in listing 6, this command finds the * words on line 10.

Compound search is particularly useful for finding a command in the code that appears after another command-for example, where a function is called after a variable is set.

Replay the search mode

When searching for patterns to replace in a file, you can have vi save any patterns you want to match in a buffer; then, when you perform a replacement, you can replay them with buffer reference numbers. The way to do this is to put the pattern between\ (and\), which instructs vi to put the pattern in a numbered buffer (1 to 9). When performing a replacement, you can reference these buffers with buffer reference numbers\ 1 through\ 9.

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

Listing 7. Replay the search pattern (previous) Martin is an IT consultant. Martin likessnowboarding and mountain biking. Martin hasworked on UNIX systems for over 15 years. Martin alsoworked for many years before that on mainframes.Martin lives in London.~~~~:%s/ ^\ (Martin\) / Mr\ 1 Wicks/g

Let's break down this command and explain it:

:% s-instructs vi to perform a replacement.

/-pattern delimiter.

^\ (Martin\)-look for the line that begins with the string Martin and save the string in buffer 1.

/-pattern delimiter.

Mr\ 1 Wicks-replace the found string with the string Mr, plus the contents of buffer 1, plus the string Wicks.

/-pattern delimiter.

G-Global modification (that is, modify all matching places).

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

The result of the modification is shown in listing 8.

Listing 8. Replay the search mode (after that) Mr Martin Wicks is an IT consultant. Martin likessnowboarding and mountain biking. Martin hasworked on UNIX systems for over 15 years. Martin alsoworked for many years before that on mainframes.Mr Martin Wicks lives in London.~~~~:%s/ ^\ (Martin\) / Mr\ 1 Wicks/g

Bookmark

You can have vi put a bookmark at a specific location in the file. You can do this by pressing the Escape key, then pressing the M key, and then entering another alphabet character that represents the bookmark reference. Therefore, there can be up to 26 bookmarks, named a to z. To return to the previous bookmark, press Escape, press the reverse apostrophe (`), and then enter the bookmark reference character.

For example, pressing the M and A keys after Escape saves the current cursor position in bookmark a. In the editing session, when you want to return to this cursor position later, just press Escape and enter `A. You can use the double reverse apostrophe (``) command to switch between the current bookmark and the previous bookmark.

Find, update, find next, repeat

One of the most useful search / replace features in the vi editor is to find a string that matches a pattern, update it, then move on to search for the next matching string, and then choose whether to update it in the same way. This is similar to the find next / replace feature in Microsoft ®Word.

You probably already know that you can search for string patterns in vi by entering command mode, typing / search_pattern (where search_pattern is a string or regular expression), and then pressing enter. Doing so will find * strings that match the specified pattern. After that, you can perform any action on the found text. For example, pressing Escape, pressing the C and W keys, and entering more text will replace the found string with another word.

To quickly find the next place to match the pattern, press Escape and then the N key. When you find the next match, you can use the dot key (.) to repeat the most recent text operation at this location, such as the modify word (cw) action used in the previous example. You can then use these keys to continue looking for other matches (n) and select repeat text operations (.) in a manner similar to using the find next / replace feature in Word.

Switch case

In vi, you can toggle the case of alphabetic characters under the cursor by pressing Escape and then pressing the tilde key (~). This switches back and forth between lowercase and uppercase. Pressing this key and moving the cursor over each character in the line will toggle the case of each alphabetic character encountered. You can enter a number before the tilde to indicate how many alphabetic characters you want to change the case of.

Screening

As you probably know, press Escape in vi, enter:! command (where command is the UNIX command to be executed), and then 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 portion of the file to the UNIX command as standard input and replace the same part of the edit buffer with the resulting output. For example, if you want the entire file shown in listing 9 to be sorted within a vi session, press Escape, type: 1 minute ordered sort and press enter, which tells vi to pass everything from the * line to the end of the file ($) to the sort command, replacing the specified part with the output.

Listing 9. Perform file sorting within a vi session (before sorting) 543276548963134sorting

Listing 10 shows the result of the sort operation.

Listing 10. File sorting is performed within a vi session (after sorting) 123334445566789 after sorting

Alternatively, you can precede the shell command with the number of lines you want to operate from the current cursor position. The way to do this is to press Escape, then enter a number for the specified number of lines, then enter two exclamation points (!), and enter the UNIX command.

For example, place the cursor at the beginning of line 4 in listing 9, press Escape, and then type:

4roomawk'{print "New text", $0}'

Press enter again, and lines 4 to 7 (inclusive) will be prefixed with the text New text, as shown in listing 11.

Listing 11. Add the new text 543New text 2New text 7New text 6New text 548963134 to precede multiple lines of code, including the print "New text", $0}'

You can use the pipe delimiter (|) to concatenate UNIX commands together to perform complex and powerful filtering in a vi session. For example, if you want to replace the contents of the file in the edit buffer of the current vi session with * space-separated fields on each line, sort them in ascending order and convert them to uppercase, type after pressing Escape:

: 1 tr tr awk'{print $1}'| sort | lower:] [: upper:]

Save part of the content

You can save some of the contents of the currently edited file by pressing Escape, and then typing: start,endw file, where start is the * line to be saved in the current file, end is the * line to be saved, w indicates that you want to write to another file (or overwrite the existing file), and file is the file to which the specified part is saved. For a * * line, you can use $to indicate the end of the file. You can use two greater than signs (> >) after w to indicate that you want to append the content to the file instead of overwriting the file. The example in listing 12 appends lines 6 to 9 inclusive to the file / tmp/newfile.

Listing 12. Save part of the file to another file (attach but not overwrite) 1 # 2 # Internet host table3 # 4:: 1 localhost5 127.0.0.1 localhost loghost6 192.168.0.6 centos57 192.168.0.10 appserv8 192.168.0.11 webserv9 192.168.0.12 test10 192.168.0.5 solaris10 # Added by DHCP~~~:6,9w > > / tmp/newfile Thank you for reading this article carefully I hope the article "what are the tips for using vi editors in linux" shared by the editor will be helpful to you. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report