The goal is simple:
- Take contents of text file
- Search for pattern
- 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]