Replace by saving specific words in vi / vim

For example, if I have $asd['word_123'] , and I wanted to replace it with $this->line('word_123') , saving "word_123". How can i do this?

Using this:

 %s/asd\[\'.*\'\]/this->line('.*')/g 

I cannot keep the wording between them. Please enlighten me.

+6
source share
2 answers

Using a regular expression, you can do something like :%s/\$asd\['\([^']*\)'\]/$this->line('\1')/g

Step by step:

%s - replace with the whole file

\$asd\[' - match "$ asd ['". Please note that $ and [ must be escaped since they have special meaning in regular expression.

\([^']*\) - \( \) can be used to select what is called an β€œatom” so you can use it as a replacement. [^'] means all is not a ' , but * means matching 0 or more of them.

'\] - ends our match.

$this->line('\1') - is replaced with what we want, and \1 replaces our matching atom earlier.

g - do this for multiple matches on each line.

Alternative (macro)

Instead of regex, you can also use a macro. For instance,

 qq/\$asd<Enter>ct'$this->line(<Esc>f]r)q 

then @q as many times as you need. You can also @@ after you use @q once, or you can 80@q if you want to use it 80 times.

Alternative (: normal)

In some cases, using :norm may be a better option. For example, if you have a short code block and you correspond to a unique character or position. If you know that "$" appears only in "$ asd" for a specific block of code, you can visually select it and

 :norm $T$ct'this->line(<Cv><Esc>f]r)<Enter> 

For a discussion about using: norm read more effectively :help :norm and this reddit post .

+19
source

Try using

 :%s/\$asd\[\'\([^\']\+\)\'\]/$this->line('\1')/g 
+1
source

Source: https://habr.com/ru/post/921172/


All Articles