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

ARB
  • 5
  • 3
  • Possible duplicate: https://stackoverflow.com/questions/24326207/using-powershell-to-remove-lines-from-a-text-file-if-it-contains-a-string – Peter Schneider Mar 13 '19 at 09:01
  • It's different. I need to delete a section wich have empty rows. – ARB Mar 13 '19 at 09: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?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Olaf Mar 13 '19 at 09: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. – Peter Schneider Mar 13 '19 at 09:25
  • Right now I have this : (Get-Content file.txt) -notmatch "other text`r`ntext 1" | Out-File file.txt . It's not working like this, something it's wrong with how i use the "`r`n". – ARB Mar 13 '19 at 09:36
  • Please [edit](https://stackoverflow.com/posts/55137481/edit) your question and put the code you have tried in there in a nice formatted way. Never put your code in a comment. – Theo Mar 13 '19 at 09:55

1 Answers1

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
AdminOfThings
  • 23,946
  • 4
  • 17
  • 27
  • 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. – ARB Mar 13 '19 at 12:03
  • I think my last example can do what you want. – AdminOfThings Mar 13 '19 at 12:38
  • 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 ! – ARB Mar 13 '19 at 13:37