I want to get the multiple lines from a text file by using a pattern with the character at the beginning of the string to the character at the end of the string,and have an output that will be copied as multiple lines also.
<#
get
these
lines
#>
I have tried using regex "<#(. )#>", it gets the lines but it copies as one string only.
Output: <# get these lines #>
CodePudding user response:
FileLines.TXT:
<# Line1 #>
## Line2 ##
<# Line3 #>
<# Line4 #>
## Line5 ##
<# Line6 #>
## Line7 ##
<# Line8 #>
<# Line9 #>
Code:
(Get-Content -Path "$PSScriptRoot\FileLines.TXT") | Where-Object { $_ -match "<#.*#>"}
Results:
<# Line1 #>
<# Line3 #>
<# Line4 #>
<# Line6 #>
<# Line8 #>
<# Line9 #>
FileLines2.TXT:
<# Line1 #>
<# Line2 #>
<# Line3 #>
## Line4 ##
## Line5 ##
<# Line6 #>
<# Line7 #>
## Line8 ##
## Line9 ##
Code:
(Get-Content -Path "$PSScriptRoot\FileLines2.TXT") | Where-Object { $_ -match "^\s*<#.*#>\s*$"} | ForEach-Object {
Write-Host "$($_.Trim())"
}
Results:
<# Line1 #>
<# Line2 #>
<# Line3 #>
<# Line6 #>
<# Line7 #>
CodePudding user response:
FileLines3.TXT:
Random info1
<#
get1
these1
lines1
#>
Random info2
<#
get2
these2
lines2
#>
Random info3
Code:
$FileContent = Get-Content -Path "$PSScriptRoot\FileLines3.TXT" -Raw
$Lines = while($FileContent -match '(?ms)^\s*<#\s*$(?<Block>.*?)#>\s*$(?<After>.*)') {
$Matches.Block.Split([Environment]::NewLine)
$FileContent = $Matches.After
}
$Lines | Where-Object {$_}
Results:
get1
these1
lines1
get2
these2
lines2