Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim find and replace. How can I do it on this?

Tags:

replace

vim

I have an XML file that I want to make some changes to. For example I want to open the file in Vim and run a find and replace all instances of memory="..." attribute to memory="24G" but only if the element is from name="node-0...". Here is an example:

process name="node-0-3" numaNode="3" memory="14G" logConfig="logback-shards.xml"
process name="node-0-4" numaNode="4" memory="34G" logConfig="logback-shards.xml"
process name="node-0-5" numaNode="5" memory="44G" logConfig="logback-shards.xml"

replace with

process name="node-0-3" numaNode="3" memory="24G" logConfig="logback-shards.xml"
process name="node-0-4" numaNode="4" memory="24G" logConfig="logback-shards.xml"
process name="node-0-5" numaNode="5" memory="24G" logConfig="logback-shards.xml" 

How can I do it in Vim?

like image 994
David Tucker Avatar asked Jan 16 '23 10:01

David Tucker


1 Answers

:g/node-0/s/memory="\zs\d\{2\}\u\ze"/24G

Step by step:

  • :g/node-0

    use the :global command to find all lines that contain node-0

  • s/memory="\zs\d\{2\}\u\ze"/24G

    1. find memory="

    2. leave it out of the actual match by starting the match here with \zs

    3. match two numbers followed by a capital letter with \d\{2\}\u

    4. the actual match ends here with \ze

    5. leaving out the closing double quotes.

    6. substitute the actual match with 24G

(edited with a more accurate pattern to suit the asker's real usecase)

edit

Using Ingo's comment:

:g/node-0/s/memory="\zs[^"]*\ze"/24G
like image 68
romainl Avatar answered Jan 23 '23 10:01

romainl