Home > Software engineering >  Find and Replace every 2nd line in a pair under certain conditions
Find and Replace every 2nd line in a pair under certain conditions

Time:01-14

I'm looking to replace multiple lines (thousands) using the following example in Notepad :

<ApplicationPath>F:\Objects\Trees\Conifers\North America\West\comporgel.zip</ApplicationPath>
<CommandLine />
<ApplicationPath>F:\Objects\Trees\Conifers\North America\West\Christmas.zip</ApplicationPath>
<Photo />
<ApplicationPath>F:\Objects\Trees\Conifers\North America\West\spruce1.zip</ApplicationPath>
<CommandLine />
<ApplicationPath>F:\Objects\Trees\Conifers\North America\East\spruce1.zip</ApplicationPath>
<CommandLine />

Where I need to search for all lines that contain the subfolder \West\ and replace the line immediately following it only if it matches <CommandLine /> with <CommandLine>trees -nowindow</CommandLine>

The output should look like this:

<ApplicationPath>F:\Objects\Trees\Conifers\North America\West\comporgel.zip</ApplicationPath>
<CommandLine>trees -nowindow</CommandLine>
<ApplicationPath>F:\Objects\Trees\Confiers\North America\West\Christmas.zip</ApplicationPath>
<Photo />
<ApplicationPath>F:\Objects\Trees\Conifers\North America\West\spruce.zip</ApplicationPath>
<CommandLine>trees -nowindow</CommandLine>
<ApplicationPath>F:\Objects\Trees\Conifers\North America\East\spruce1.zip</ApplicationPath>
<CommandLine />

CodePudding user response:

Set the search to Regular expression mode:

Notepad   search box showing this search

Find what: ^(<ApplicationPath>[^<]*?\\West\\[^<] ?</ApplicationPath>\r?\n)<CommandLine />

Replace with: \1<CommandLine>trees -nowindow</CommandLine>

CodePudding user response:

Assuming your are using something like Notepad , which supports full regex replacements, you may try the following:

Find:    (<ApplicationPath>.*\\West\\.*<\/ApplicationPath>\n)<CommandLine \/>
Replace: $1<CommandLine>trees -nowindow</CommandLine>

Here is a demo.

  •  Tags:  
  • Related