0

I'm trying to substring a substring of a text file in order to cut out the text I need from a text file.

In this example if the file contains the following

this is a test example
second line of text
third line of text

I want to remove everything before second, then get everything between "second" and "third line". So the output would be

second line of text
third line

This is what I have and it works if put a hardcoded length in $second, but I can't get the length correct as a variable:

$text = ( Get-Content -raw Test.txt | Out-String ).Trim() 

$first = $text.IndexOf('second')

$second = $text.Substring($text.IndexOf('second'), ($text.length-1))

$third = $second.Substring(0, $second.IndexOf('third line'))

$text.Substring($first, $third) | Set-Content file2.txt

2 Answers 2

1

couple of ways you could do this:

first- specify what you dont want

Get-Content -Path textfile | 
  Where-Object {$_ -NotLike 'this is a*'} | 
    Set-Content file2.txt

second- specify what you do want

Get-Content -Path textfile | 
  Where-Object {$_ -Like 'second*' -or $_ -like 'third*'}  | 
    Set-Content file2.txt

or

Get-Content -Path textfile | 
  Where-Object {$_ -match '^(second|third)'}   | 
    Set-Content file2.txt
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, Thank you!
0

Here I was getting text data and then splitting it by single line (`n) doing so will make an array of string lines. Then I get strings number by array enumeration [1..2].

PS C:\> $string = @"
this is a test example
second line of text
third line of text
"@

$string.Split("`n")[1..2]
second line of text
third line of text

1 Comment

Thank you for your help but my real file is a lot larger than the example so not sure how to translate it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.