Wim will find and replace. How can i do this?

I have an XML file that I want to make some changes to. For example, I want to open a file in Vim and run find and replace all instances of the attribute memory="..." with 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

 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 this in vim?

+4
source share
3 answers
 :g/node-0/s/memory="\zs\d\{2\}\u\ze"/24G 

Step by step:

  • :g/node-0

    use :global command to find all rows containing node-0

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

    • find memory="

    • leave it outside the actual match by running the match \zs

    • correspond to two numbers followed by a capital letter with \d\{2\}\u

    • the actual match ends here \ze

    • leaving closing double quotes.

    • replace actual match with 24G

(edited with a more accurate drawing, suitable for a true user-user)

change

Using Ingo's comment:

 :g/node-0/s/memory="\zs[^"]*\ze"/24G 
+8
source

you can use single line sed if you don't want to open vim every time:

 sed -i '/node-0/s/memory=".\{3\}/memory="24G"/' foo.txt 

or you can use the same command from inside vim using:

 :%!sed '/node-0/s/memory=".\{3\}/memory="24G"/' 
+1
source

If all lines have the same format, you can try the following:

f 1 // to go to "14G" in your first line

Ctrl + v // start visual block mode

2 j // to select [1] 4G, [3] 4G, [4] 4G

r 2 // replace with 2

0
source

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


All Articles