1

The goal is simple:

  1. Take contents of text file
  2. Search for pattern
  3. Save search back to the file

For example, i want to find the first occurrence between # and ##. Following regex works perfectly (\#)(.*?)(?=\#{2}). It finds what I want. However, PowerShell removes all new line characters effectively changing the formatting. So, following input text

#
This
Is
My
Text
##

becomes this

# This Is My Text

How to preserve the formatting?

Here is my PowerShell script

param (
    [string]$filename
)

$content = Get-Content -Path $filename
$output = $filename

$regex = [Regex]::new('(\#)(.*?)(?=\#{2})')
$matches = $regex.Matches($content)
Set-Content -Path $output $Matches[0]
Ingweland
  • 1,073
  • 1
  • 13
  • 25

0 Answers0