Ritu
Ritu

Reputation: 7

Replace all the lines between two lines using powershell

I have a Config file and I want to replace all the lines between two lines using powershell Here is my code:

 $HttpPath = "C:\Oracle\Middleware\Oracle_Home\user_projects\domains\my_domain\config\fmwconfig\components\OHS\ohs1\httpd.conf"
 $NewLine = 'Options -Indexes'
 $Pattern = '(?<=<Directory />).*?(?=</Directory>)'
(Get-Content -Path $HttpPath -Raw) | ForEach-Object {
  $_ -replace $Pattern,$NewLine
 } | Set-Content -Path $HttpPath

Here is text of config the file:

 <Directory />
 AllowOverride none
 Require all denied
 </Directory>

I want to replace two lines of "Hi" and "Hello" with one line "Options -Indexes". Result should look like:

<Directory />
Options -Indexes
</Directory>

This script works if the file content be like:

<Directory /> AllowOverride none Require all denied </Directory>

Then Output be like:

<Directory />Options -Indexes</Directory>

But as the content of file splits in separate lines, this does not works.

Upvotes: 0

Views: 670

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

You can do the following:

$Pattern = '(?s)(?<=<Directory />\r?\n).*?(?=</Directory>)'
$NewLine = "{0}{1}" -f 'Options -Indexes',[Environment]::NewLine
(Get-Content http.conf -raw) -replace $Pattern,$NewLine | Set-Content http.conf

Explanation:

Using the -Raw switch of Get-Content allows you to work with multiple lines without having to store previous line outputs. It reads the entire file as a single string instead of an array of strings.

The s modifier (used with syntax (?s)) is the single-line modifier. It allows the regex character . to match newline characters, which you will have since your target text is between two other lines.

The mechanism (?<=text) is a positive lookbehind assertion from the current position. It expects text to be behind the current position. \r?\n matches 0 or 1 carriage return and 1 newline. text will not be removed here.

The mechanism (?=text) is a positive lookahead assertion checking that text is ahead of the current position. text will not be removed here.

-f is the string format operator. This is not required, but it is a useful way to construct a string with programmable parts.

Upvotes: 0

Related Questions