Reputation: 21
I have a .txt
file that has a structure like this.
Configure text Example
Configure text Example
Configure text Example
---Start of Data---
Data I want to grab
Data I want to grab
Data I want to grab
Data I want to grab
---End of Data---
What would be the best way for me to grab the data between the two rows (Start of Data & End of Data)?
Upvotes: 2
Views: 827
Reputation: 2457
Regex would be your best bet here, it seems.
$file = "data.txt"
$pattern = "---Start of Data---([\s\S]*?)---End of Data---"
$string = Get-Content $file -Raw
$result = [regex]::match($string, $pattern).Groups[1].Value
$result
will contain the output that you want.
Upvotes: 2
Reputation: 5114
In addition to Yash's great answer, here is some fun stuff you can do with switch
if you want to catch different parts or sections that are identifiable by some start and end line
$text = @'
Configure text Example
Configure text Example
Configure text Example
---Start Part A---
Data I want to grab
Data I want to grab
Data I want to grab
Data I want to grab
---End A---
Some other text that isn't needed
Some other text that isn't needed
---Start Section B---
Data I want to grab in B
Data I want to grab in B
Data I want to grab in B
Data I want to grab in B
Data I want to grab in B
---End B---
'@ -split '\r?\n'
$inside = $false
$pattern = '---(?:Start|End) ?(\D+?)---'
switch -Regex ($text) {
$pattern {
$inside = !$inside
$section = $Matches[1]
}
default {
if ($inside) {
[PSCustomObject]@{
Section = $section
Line = $_
}
}
}
}
Output
Section Line
------- ----
Part A Data I want to grab
Part A Data I want to grab
Part A Data I want to grab
Part A Data I want to grab
Section B Data I want to grab in B
Section B Data I want to grab in B
Section B Data I want to grab in B
Section B Data I want to grab in B
Section B Data I want to grab in B
Upvotes: 0