Replace the content with the s and g commands in the vim editor.

Source: Internet
Author: User
Differences between vimgs replace and global commands are one of Vim's most powerful commands (I think it is No. 1). If you are familiar with them, you can get twice the result with half the effort. This article summarizes some classic problems of the version, based on your own usage and understanding, I try to introduce its usage in detail through the instance. The examples are difficult. Some examples are not practical and are generated for the question. Differences between vim g s replacement

The global command is one of Vim's most powerful commands (I personally think it is No. 1). you can get twice the result with full familiarity with it,
This article summarizes some of the classic issues on the version. based on your usage and understanding, I try to introduce them in detail through examples.
Its usage. The examples are difficult. Some examples are not very practical. if you are born with questions, you may need them. Example:
It is not very meticulous to avoid Luo Yun. The positions of the involved content in Vim help are listed under the heading of each section.
For search. The words in this article are not necessarily standard (I have not read Vim's help in Chinese), and there are also mistakes in my opinion. please correct me!

1. global command format

: H: g

: H 12.4

: [Range] global/{pattern}/{command}

The global command searches for {pattern} within the text range specified by [range] (the entire file by default), and
Run the command {command} on the matched line. if you want to execute the command on a line that does not match, use global! Or vg
Lobal command.

Let's take a look at a classic example in the Vim user manual.

[Example 1] inverted file line (that is, the tac command under unix)

: G/^/m 0

This command marks/^/at the beginning of the line to match all lines of the file (this is a common technique for searching, if/./is used, it is
Match non-empty lines, less than the requirements of this example), and then use the move command to move each line to the first line (the next line of 0th)
Rows) to implement the reverse order function.

The global command is actually executed in two steps: first, scan all rows within the range specified by [range], and match {pa
Ttern} rows are marked. then, execute the {command} command on the marked rows in turn. if the marked rows are
If a Command operation that matches a row is deleted, moved, or merged, its flag disappears automatically and the row is not executed
{Command} command. The concept of tag is very important, for example.

[Example 2] delete an even number of rows

: G/^/+ 1 d

This command matches all rows and then deletes the rows (where + 1 is used to locate the next row of the current row ). Why
Is it a line break? Because the second line is deleted when the + 1 d command is executed on the first line, while the second line is also marked
But does not exist, so the command to delete the third line will not be executed.

In this example, you can also use the normal command:

: % Norm jdd

% Specifies the entire file, and then execute jdd in normal mode in sequence, that is, move down and delete a row. Different from the global Command
% Norm is executed in the order of row numbers. the second row is deleted in the first row, and all subsequent row numbers are subtracted.
1. Therefore, when jdd is executed in the second row, the fourth row is deleted. That is to say, the global Command uses an even number
The line mark is removed, while the normal command is implemented by the automatic forward of subsequent lines.

[Example 3] delete odd rows

: G/^/d | m.

The light is: g/^/d obviously does not work. This will delete all rows. we need to use the move command to remove the mark of the even rows. When
However, this example can be easily converted to [example 2], which is only used to emphasize the concept of tag.

In this example, if you want to use the normal command for implementation, % norm dd will also delete the entire file, % norm jkdd
I don't know why the two are different. they may be related to the internal running mechanism of the normal command.

2. global and substitute

: H 10.4

: Helpg ms-wordc

Many vimmer think that these two commands are similar. Indeed, they are similar in the form of searching and matching,
However, the substitute command replaces other commands executed by global (of course, the default [r
Ange] is the current row, which is also different ). Let's take a look at two examples to see how s and g think differently.

[Example 4] all double rows

: % S/. */& r &/

: G/^/t.

Substitue is to search for any row, and then replace it with the two-row folder and press enter; global is to copy each row (t is: co
Py) to your own, more clear.

[Example 5] text segmented by carriage return is converted into text segmented by carriage return.

Many txt ebooks and text such as vim help have limited characters in each line, and empty lines are used between segments.
Separated. If you copy them to the word, the hard carriage return and empty lines will be annoying, although the word also has automatic
Adjust the format function, but it is a piece of cake in Vim. First, let's see how to implement it with replacement.

: S/nn @! //

Nn @! Is to find the carriage return that is not followed by the carriage return (about @! Usage: h /@!, ), And then
Replace it with a space, that is, remove the carriage return used for typographical input. The global command is completely another way of thinking.

: G/./,/^ $/j

/./Mark non-empty rows,/^ $/search for the empty rows after them, and then merge the rows between them. Some may
Q: Will the j command be executed for each line in the segment? As mentioned above, Mark rows lost in previous operations
If you do not execute the operation command, the other lines in the segment have been merged when processing the first line of each segment. Therefore, only
Run the j command once. This command uses the global flag as the starting line of [range ].
.

Global is often used in combination with substitute. The former is used to locate rows that meet certain conditions, and the latter is used in these rows.
Find and replace. For example:

[Example 6] replace aaa with bbb unless the row contains ccc or ddd

: V/ccc | ddd/s/aaa/bbb/g

[Example 7] replace aaa with bbb, if the row contains ccc but cannot have ddd

How do I write a regular expression that matches aaa and satisfies the condition that the row has ccc but not ddd? I don't know. Even if you can write
It must be extremely complicated. Using the global command is not difficult:

: G/ccc/if getline ('.')!~ 'Ddd '| s/aaa/bbb/g

This command first marks the line that matches ccc, and then runs the if command (if is also the ex command !), Get the getline function
The current row, and then determine if it matches ddd. if it does not match (!~ Is replaced. Master this
The usage of the sample requires a certain understanding of the ex command, Vim function, and expression. In fact, this command is already
A quick version of the script. Some may think, isn't it enough to connect g and v? Unfortunately, the global command does not support
Nesting.

3. [range] Usage of the global flag

: H range

The flag set in the first step of the global command can be used to set various forms of [rang
E]. This technique has been used in both [example 2] and [example 5], and flexible use of [range] is an important basic
. Let's take a look at the general problems of [example 2] and [example 3.

[Example 8] delete m rows before/after n rows (for example, delete 3 rows before/after each 10 rows)

: G/^/, + 2 d |, + 6 m-1

: G/^/, + 6 m-1 | + 1, + 3 d

The two commands still use move to clear the flag of the reserved rows. Note that the current
The line is the location where the first command is addressable and executed. Let's look at two more practical examples.

[Example 9] extract the conditional compilation content. For example, in a multi-platform C program, there are a lot of conditional compilation code:

# Ifdef WIN32

XXX1

XXX2

# Endif

...

# Ifdef WIN32

XXX3

XXX4

# Else

YYY1

YYY2

# Endif

Now we use the global Command to extract the code on the Win32 Platform and copy it to the end of the file:

: G/# ifdef WIN32/+ 1,/# else | # endif/-1 t $

The [range] of the t command is separated by commas. the starting line is/# ifdef WIN32/mark the next line of the line, and the ending line is 1.
Search location, which appears after the start line # endif or # else, t copies the content between the two
End.

[Example 10] extract the code of the non-Win32 Platform in the above C program (part YYY)

First of all, this example is much more complex than lift, mainly involving [range] operations, and has been compared with glo
It doesn't matter much about the bal command. The purpose of adding this parameter is to finish the problem for your reference.
The complexity of this example is: first, you cannot simply use # else and # endif for locating, because the code may have other
Conditional compilation, we must limit the search range to # ifdef WIN32 block. In addition, in the block
It does not have the # else part, which will cause a lot of trouble for positioning. Solution:

: Try | g/# ifdef WIN32 // # else/+ 1,/# endif/-1 t $ | endtry

Regardless of try and endtry, check the global part in the middle: find WIN32, then find # else, and
The row is used as the starting line of [range], and then from the current cursor (row where WIN32 is located, not the next line of # else just found)
Line) find # endif, use the previous line as the end line of [range], and then execute the t command. But
# Else block, such as the first code, the starting line of [range] is YYY1, and the ending line is XXX2 (because of the search #
Endif starts from the first line, rather than from YYY1). This is an invalid [range] and causes
Ception. if it is not placed in try, the global Command will immediately stop.

Unlike commas (,), if [range] is separated by semicolons (;), the current cursor is moved to the starting line.
When you look for # endif, it starts from the next line of # else. this produces an invalid [range]. try is not needed, but the question is
Question: If no # else block is found, the # else part in the block is found incorrectly.

4. global and Vim scripts

: H script

: H expression

Some people often ask: what functions does XxEditor have? does Vim support? It is probably not supported because Vim is not a feature
User groups provide non-general functions, but few functions cannot be customized in Vim,
Add it to your vimrc or plugin. Script is a powerful tool for customizing Vim. This article does not discuss writing scripts
It introduces how to use global to implement similar script functions. In fact, it uses the mechanism provided by commands,
Make a simplified script.

[Example 11] calculate the sum of numeric columns in a file (or other operations)

: Let I = 0

: G/^/let I + = str2nr (getline ('.'))

: Echo I

First, define the variable I and clear it. Then, use the str2nr function to convert the current row into a number and accumulate it into I. Note that Vim does not support
Floating point number. Global actually replaces the for loop in the script.

One of the most common problems in Vim is how to generate a column of incremental numbers. There are many solutions: calling external commands, recording
Macro, using the substitute command, there are dedicated plug-ins, and using the global Command can achieve some more advanced functions
Yes. See the following example.

[Example 12] add a label to a valid code line

In the book _ Data Structures and Algorithm Analysis inC _, the author
Add a comment on the valid line in the code, for example:

Unsigned int factorial (unsigned int n)

{

If (n <= 1)

Return 1;

Return (n * factorial (n-1 ));

}

In order to align after adding labels, we insert enough spaces before each line of code (this is of course very simple)
), And then use the global Command to automatically add the label:

: Let I = 1 | g/a/s/{8}/= printf ("/*-*/", I)/| let I + = 1

The variable I is used to record the number. The g Command searches for rows with letters and replaces the first eight spaces with the comment number.
After the row processing is complete, add one. /= Is used in replacement, a very useful function.

5. Summary

Using the global command is not easy. every part of the command is worth studying carefully: only the range principle is mastered.
Can be freely located in the file; only proficient in pattern can effectively match the desired line; only familiar
With the ex command, you can select the most suitable function for operations. only variables, expressions, functions, and other content can be specified.
To enable the global command to implement the script function. In short, global is a very good framework for Vi
The more familiar m is, the more powerful it can set up and use its various weapons.

Of course, global is not omnipotent, and its functions are lacking. The main problem is that it can only use regular expressions to mark matching.
Line. if any expression can be used to mark (or from another angle, as described by runsnake, the former mv moderator
Evaluate the regular expression) to achieve more convenient functions. For example
There are simple and unified solutions. The preceding example uses specialized text processing tools such as sed and awk, or perl
Similar script languages are not difficult, and some implementations are more convenient. The Vim solution provided in this article is not necessarily simple.
Single, or even difficult to understand, aims to introduce the use of global. For those that do not or cannot use
Its tool may be more valuable for reference. In fact, Vim has rich functions and deserves further study.
. For an inappropriate example, Shaolin's stunt is certainly superb, and the more it will be, the stronger the natural skill, but as long as it will
The last six-pulse magic sword or a little useless power is enough to be unique.

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.