当前位置:网站首页>VIM from dislike to dependence (19) -- substitution

VIM from dislike to dependence (19) -- substitution

2022-06-27 08:24:00 aluluka

Previously discussed about vim The knowledge of regular expression can be easily searched in , Now, let's continue to discuss how to perform the replacement operation based on the previous work .

substitute brief introduction

substitute Allow us to find a piece of text and replace the matching text with the new text . Its use is complicated , You need to provide a matching pattern and a replacement string . The command format is as follows :

:[range]s[ubstitute]/{pattern}/{string}/{flag}
  • range Scope of representation , It is different from the others mentioned before ex The scope of the command is the same .
  • pattern Represents a matching pattern , Recall what I said before , The mode here is the same as the normal mode introduced before 、 The meaning of the insert pattern is different , It represents a string used for matching and highlighting .
  • string Is a string used for replacement , Replace all the matching items with something .
  • flag Are some replacement flags , We will introduce it later .

for example :%s/python/Python/g Indicates that... Will be used throughout the file python Replace with Python( I haven't mentioned it for such a long time ex The command , I wonder if you guys still remember % Represents the currently open file ).g It's a marker bit , Means to modify all matches in the whole row , Instead of just modifying the first match .

Sign a

In the above example, we used a g As a flag , In fact, there are other flag bits . We can flexibly define through the flag bit substitute act . Here are some commonly used flag bits :

  • \r: Insert a line break
  • \t: Insert a tab
  • \\: Insert a backslash
  • \1: Insert first child match
  • \2: Insert the second child match
  • \0: Insert all the contents of the matching pattern
  • &: And \0 The usage is the same
  • ~: Use the last call substitute Provided by string Content
  • \={vim script}: perform vim script And return the content as string

There are so many flags , How to remember , How to use it at ordinary times ? Don't worry. , The following will demonstrate how to use them through corresponding examples , We can learn them in our daily use .

Example

Use g Replace everything

how can I learn python very good, just use it more and more.
python is very powerful, you can just learn python within your work.

We will all of the above text python All changed to vim . Let's take a look at what it looks like to not use the logo . Enter here :%s/python/vim
 Insert picture description here
We find that it only replaces the first occurrence of each line python The place of , After the same line python Unaffected . Here we use /g Replace every occurrence python The place of .

 Insert picture description here
g This sign is easy to associate with global The word , It should represent the entire selected text range , We have previously selected all the text in the current file , It seems reasonable . however g The scope should be the entire line , And we selected all the lines in the text . It looks the same , But there is a gap in understanding . Why does it work on rows , I think so vim Originated in ed This editor ,vim Of ex The command originated from ed Editor , The latter is a line editor , So most of the commands work on the line . This should make sense .

Manually select whether to replace

Sometimes we don't want to blindly replace everything , And replace only part of it . For example, in the above text , We just want to replace the last one on the second line python by vim. Then you can use c sign . You can understand it as copy ?.vim Will ask if we need to replace . That is, we enter here :%s/python/vim/gc. You can press... At the back y To determine the replacement ,n It means not to replace and switch to the next match . So here we can enter nny
 Insert picture description here
Actually not only yn These two options , from vim There are... In total ynaql and <Ctrl +e> as well as <Ctrl + y>. Their meanings are as follows :

  • y: Replace this match
  • n: Do not replace this match
  • a: Replace all matches after here , Then exit this replacement
  • q: Exit this match
  • l: Exit this replacement after replacing here
  • <Ctrl + e>: Scroll the screen up
  • <Ctrl + y>: Scroll down the screen

Reuse the last matching pattern

If we were to {pattern} Leave some blank , that vim Will reuse the last {pattern} . Let's use an example to see how to use this feature .

#define VERSION "v1.01"
#define TITLE "vim"
#define PATH "~/.config/nvim"

We want to change the string to a wide character , That is, before the double quotation marks L We first need to match all the quotation marks . A lot of times regular expressions are complicated , You can't write it right all at once , So here we go step by step , First, write the regular expression correctly to match all strings with double quotation marks . \v"(.*)" You can get all the strings .
 Insert picture description here
Then we use the above pattern to replace , The input :%s//L\0/gc. Of course, there are only three lines here to know at a glance that we are going to replace all , But the code is long , We need to confirm whether it needs to be replaced .
 Insert picture description here
We can't get complex regular expressions right all at once , If you have to re-enter a lot of content every time because the regular expression is not entered correctly during the replacement operation, it will be more troublesome . And if you use substitute After the command, I found that I was wrong , You have to cancel and re-enter such a large string . And substitute comparison , Find mode does not modify the text , We can use... In lookup mode <Up> Revise slowly until you are satisfied . When the pattern is right , Now you can use {pattern} Leave blank this way to reuse the last pattern .

Note that the pattern is left blank , Will leave an incomplete record in the history command , Patterns and commands are stored independently . In the example above , If I perform a new match , For example, I want to find all define, Use... In the back When you re execute the command , It is found that the matching content has changed . One way is to store the last mode in a register , When matching, take data from the register to fill {pattern} part .

How to put the corresponding pattern into the register after the last match is successful , Here we introduce a new content —— Command window . The command window is a buffer that displays historical commands , It differs from a normal buffer only in that it displays historical commands . Use q: You can call up , Here we can use q/ Call up the command window of the mode . Use... In the corresponding mode line "iy$ To paste a line , Then use... For the final replacement <C-r>i Fill in {pattern}.
 Insert picture description here
 Insert picture description here

Sometimes it's convenient and sometimes it's troublesome to use the move of leaving blank , How to use the above two methods? Please make your own judgment based on the specific situation .

Replace with the contents of the register

{pattern} The field is left blank ,vim Will automatically match the previous pattern , So if I leave the replacement field blank , Will the string replaced in the previous time be replaced as this time ? After the test, it was found that vim It doesn't do that , It will replace with an empty string ( Simply use the last replacement string ~ This symbol ). If you want to quickly fill in replacement fields , You can copy first , And then in substitute Use in 0 register . namely , We can type in :%s/{pattern}/<C-r>0/gc To complete the replacement . Just like the example above .

But this approach has one drawback , That is, if there is / & And other special symbols , It will have errors . At this time, we can manually edit the contents of the register , Escape special symbols . At this time, we will wonder if there is any way to make vim You know, I just want to treat the special symbols in the register as ordinary strings ? Of course, there is a way , We can use vim script To fulfill this need . We can type in :%s/{pattern}/\[email protected]/gc, among \= It is the use we listed before vim script, And then there's @0 It is vim script The content of , It means take 0 The contents of the register .

It's here vim script The content of , But don't worry , What is involved here is the simplest vim script Content , And the update is finished vim After that, a new column will be opened to introduce vim script and vim Configuration of , At that time, it's OK to look back at this method . This script is also easy to understand ?

Use the last substitute command

Suppose we are performing substitute I forgot to add... Before the command %, Of course we can use <Up> Key to modify the previous time .

Here is a simpler way , You can enter... In normal mode g& It will re execute the previous item in the entire file substitute command . It is equivalent to :%s//~/&. When the rest of you are right , Only forgot to add % Consider using this command .
 Insert picture description here
Let's look at another situation :
Suppose I have such a piece of code

mini = {
    
  applyName: function(config){
    
    return obj.factory(config, this.getName());
  },
}

I'm going to add a new function to this , Make it like this

mini = {
    
  applyName: function(config){
    
    return obj.factory(config, this.getName());
  },
  
  applyNumber: function(config){
    
    return obj.factory(config, this.getNumber());
  },
}

We found that , Simply copy the previous function , And then Name Change it to Number That's all right. . We can use :%s/Name/Number/g To perform a replacement , But one problem is that it replaces all the content . Fortunately, it can be used once u To undo all changes .
 Insert picture description here
I introduced the command mode , Most of ex All commands can use the selected part in the selection mode as the execution range of the command ,substitute Can also be . Let's first select the part to be changed later , And then use :&& To repeat the last... In the selected part substitute command . these two items. & It has a different meaning , first & It means to repeat the last execution substitute command , But it does not contain the last specified flag bit , Add another one at the end & Indicates that the last flag bit is repeated . hinder & With the above g& Medium & The meaning is the same .
 Insert picture description here

Replace with a sub match

Suppose I have such a contact record

Jack Ma, 12398988011
Pony Ma, 16528649018
Donald Trump, 15092838173
Joe Biden, 18571820986

Now I want to change the order , Put the phone number first , The person's name comes after .
First, we construct a regular expression that can accurately match the names of people and phone numbers : (.*),\s+(\d{11}) . The first bracket matches the person's name , The second bracket matches the phone number 11 An integer .
 Insert picture description here
Then we can take advantage of the {pattern} The way to leave blank , Reorganize the new arrangement :%s//\2, \1
 Insert picture description here

Use vimscript Script

In the above introduction to reading contents from registers for replacement, I preliminarily introduced , Use vimscript Example . Here we give another use vimscript Example , But don't panic , The scripts used are extremely simple , There are no barriers to understanding .

Suppose there's a period like this HTML Code

<h2> this is a h2 tag</h2>
<h3> this is a h3 tag</h3>
<h4> this is a h4 tag</h4>
<h5> this is a h5 tag</h5>

We want to upgrade the title tag , In other words, it will <h2>, Upgrade to <h1>,<h3> Upgrade to <h2>.

First, we construct a pattern to match the corresponding number , It can be used \d To match numbers , But it will match all the numbers , So we add a limit , Match only with <h perhaps </h Number at the beginning , At this point, the regular expression can be changed to \<\/?h\d, We just want the following numbers , So you can crop this match ,\<\/?h\zs\d. This will match all the numbers after the tag , But the numbers in the content are not matched .
 Insert picture description here
Then we introduce a new vimscript command ——submatch, It receives a parameter indicating the number of matches , Return the corresponding match . We can use this function to get every match -1, The input :%s//\=submatch(0)-1/g You can complete this operation .
 Insert picture description here

Final summary

In this article, I focus on substitute The use of this command , Describes the flag bits corresponding to this command , Some examples are given to demonstrate how to use these flag bits . I believe you have a certain understanding of the replacement order .

You guys may have doubts , At present, it seems that the search and replace introduced is only for a certain file , What if I want to make a global replacement in the project ? Please think about how we run macros in multiple files . This part will not be introduced , It can be regarded as an exercise . As for multiple files to find , We will continue in the following sections .

原网站

版权声明
本文为[aluluka]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270812111059.html