Royce
Royce

Reputation: 585

Powershell regex, selection until specific string


I'm not really goot at regex and tried for days to find the right powershell regex for the following situation:
Assuming I have the following input file:
/export/home/ blabla1 blabla2
/export/home/ blabla3 blabla4
/export/home/ blabla5 blabla6
I need a powershell regex expression that separates the selection including /export/home/ until the next /export/home/ appears.
Do you have any ideas?
Thanks in advance

Upvotes: 0

Views: 299

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174515

Easiest way to do what you're trying to accomplish is doing a -split with a zero-length delimiter:

(Get-Content .\file.txt -Raw) -split "(?!^)(?=/export/home/)"

The right-hand argument basically says "split when":

(?!^) # not at start of string
(?=/export/home/) # next match is /export/home/

You can remove trailing newlines with TrimEnd():

$Delimiter = '/export/home/'
$Escaped   = [regex]::Escape($Delimiter)
$Split     = "(?!^)(?=$Escaped)"
$Result    = (Get-Content .\file.txt -Raw) -split $Split |ForEach-Object { $_.TrimEnd() }

Upvotes: 2

Related Questions