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
-
what do you mean with '..separates the selection.." ???CB.– CB.2015-10-23 09:23:06 +00:00Commented Oct 23, 2015 at 9:23
-
I mean that i like to select everything including /export/home/ until the next /export/home appears. I used to use get-content but it's possible that there are several line breaks until the next /export/home/ appears. As far as i know get-content selects every single line. I would need multiple lines (depending on when /export/home/ shows up)Royce– Royce2015-10-23 09:29:32 +00:00Commented Oct 23, 2015 at 9:29
Add a comment
|
1 Answer
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() }
1 Comment
Royce
Thanks Mathias, that's exactly what I need :)