Delete content between two lines

I have a pacfile that I am trying to update and I need to delete the content between two lines; the lines themselves must be preserved:

 // OFFICE 365 DIRECT ACCESS

      

and

// END OFFICE 365 DIRECT ACCESS

      

Example:

// OFFICE 365 DIRECT ACCESS
  if (isInNet(hostip, "23.103.132.0","255.255.252.0") ||    //EOP
  isInNet(hostip, "23.103.136.0","255.255.248.0") ||    //EOP
  isInNet(hostip, "23.103.144.0","255.255.240.0") ||    //EOP
  isInNet(hostip, "23.103.191.0","255.255.255.0") ||    //EOP
// END OFFICE 365 DIRECT ACCESS

      

I want to delete lines between top and bottom lines

$Pacfile = Get-ChildItem .\o365.pac | Get-Content -Raw
$startstring= " \/\/ OFFICE 365 DIRECT ACCESS(.*? )\/\/END OFFICE 365 DIRECT ACCESS"
$NewPacfile = [regex]::match($Pacfile, $startstring).Groups[1].value
$NewPacfile

      

+3


source to share


1 answer


$regex=@'
(?ms)^(\s*// OFFICE 365 DIRECT ACCESS\s*?\r?\n).*?\r?\n(\s*// END OFFICE 365 DIRECT ACCESS\s*)
'@
(Get-Content -Raw .\o365.pac) -replace $regex, '$1$2'

      



  • -replace $regex, '$1$2'

    replaces what the regex matches what matches the 1st ( $1

    ) and 2nd capturing ( $2

    ) groups (nested subexpression, (...)

    ). Here, these capture groups are capturing lines that span the range of interest.

  • (?ms)

    sets both m the top line and the s option for the regular expression:

    • m

      means that ^

      and $

      must match the beginning and end of each line, not the input string as a whole.
    • s

      means that the metacharacter .

      must match characters \n

      , so an expression such as .*

      can be used to match between strings.
  • \r?\n

    matches one line break, both CRLF and LF.

  • .*?

    matches the part to be removed; note the unwanted ( ?

    ) modifier following .*

    , which ensures that the next occurrence of the final string matches.

+3


source







All Articles