0

I need to delete/replace specific text which is written on more rows and has blank rows between the lines of text.

For example:

some text

text 1

other text

text 1

I need to delete:

other text

text 1

The result will be:

some text

text 1

Right now I have this: (Get-Content file.txt) -notmatch "other textrntext 1" | Out-File file.txt

6
  • Possible duplicate: stackoverflow.com/questions/24326207/… Commented Mar 13, 2019 at 9:01
  • It's different. I need to delete a section wich have empty rows. Commented Mar 13, 2019 at 9:13
  • 1
    You missed to show the code you have so far. You might read the following help How do I ask a good question? and How to create a Minimal, Complete, and Verifiable example. Commented Mar 13, 2019 at 9:19
  • The sample should get you started... use the get-content cmdlet with the -raw parameter then you can use \r\n inside the -pattern parameter of select-string to match the newline. As stated by Olaf you should provide some code. Commented Mar 13, 2019 at 9:25
  • Right now I have this : (Get-Content file.txt) -notmatch "other textrntext 1" | Out-File file.txt . It's not working like this, something it's wrong with how i use the "rn". Commented Mar 13, 2019 at 9:36

1 Answer 1

0

There are a number of ways to approach this.

Grabbing the first three lines of the text file:

(Get-Content File.txt)[0..2]

Selecting the string you wish to output:

((Get-Content File.txt -raw) | Select-String -pattern "(?s)some text.*?text 1").matches.value

Determining line numbers of bad lines and then excluding them:

$File = Get-Content File.txt
$FirstBadLine = $File.IndexOf("other text")
$LastBadLine = ($file | select -skip $firstbadline).IndexOf("text 1")+$firstbadline
$file[0..($firstbadline-1)],$file[($lastbadline+1)..$file.count]

Determine First Bad Line and skipping a known number of lines from there:

$File = Get-Content File.txt
$NumberOfBadLines = 5
$FirstBadLine = $File.IndexOf("other text")
$file[0..($firstbadline-1)+($firstbadline+$NumberOfBadLines)..$file.count] | Set-Content File.txt
Sign up to request clarification or add additional context in comments.

3 Comments

I tried to give an simpler example. What I have is one file with a lot of lines and I need to delete a section wich have 5 lines ( 3 liness with text and 2 empty lines between). I don't know the numer on which the lines are.
I think my last example can do what you want.
Your last example saved me. I knew the third row and the fifth and I searched the third row and did $firstBadLine-2. Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.