当前位置:网站首页>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
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 .
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
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 .
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 .
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}
.
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 .
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 .
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 .
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 .
Then we can take advantage of the {pattern}
The way to leave blank , Reorganize the new arrangement :%s//\2, \1
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 .
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 .
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 .
边栏推荐
- ACM course term summary
- After working in a large factory for ten years with an annual salary of 400000 yuan, I was suddenly laid off. If the company wanted to abandon you, it wouldn't leave any kindness
- SQL Sever column name or number of supplied values does not match the table definition
- 【批处理DOS-CMD命令-汇总和小结】-将文件夹映射成虚拟磁盘——subst
- 一种太阳能电荷泵供电电路的方案设计
- 准备好迁移上云了?请收下这份迁移步骤清单
- How much do you know about the cause of amplifier distortion?
- Binary tree structure and heap structure foundation
- Online text digit recognition list summation tool
- ArrayList和LinkedList的区别
猜你喜欢
随机推荐
[batch dos-cmd command - summary and summary] - output / display command - echo
SIG associé: toutes les routes mènent à ue5
分析日志.log
orthofinder直系同源蛋白分析及结果处理
c#的初步认识
2022.06.26(LC_6100_统计放置房子的方式数)
JVM common garbage collector
c的时间函数算效率
March into machine learning -- Preface
【云原生】2.3 Kubernetes 核心实战(上)
2022.06.26(LC_6101_判断矩阵是否是一个 X 矩阵)
[notes on c++ primer] Chapter 3 string, vector and array
Redis主从复制以及哨兵模式
Order by injection of SQL injection
关于放大器失真的原因你了解多少呢?
How can I import data from Oracle into fastdfs?
SQL Sever column name or number of supplied values does not match the table definition
MySQL环境变量配置的教程
What is futures reverse documentary?
Redis configuration file details