Search code examples
regexnotepad++

Find and Replace every 2nd line in a pair under certain conditions


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 />

All I know to do is go to Search -> replace but I don't know how to find this:

<ApplicationPath>F:\Objects\Trees\Conifers\North America\West\RANDOMTEXT.zip</ApplicationPath>
<CommandLine />

and replace only the commandline section with <CommandLine>trees -nowindow</CommandLine>.


Solution

  • 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>