coinbird
coinbird

Reputation: 1217

Find and replace in PowerShell

My PowerShell script reads a big text file and does a bunch of stuff to it. The part I'm stuck on is how to edit an entire line of text based on part of it.

For example, this line is in my text file:

Blah Blah 123

I would use this PowerShell:

$FileContents=$FileContents.Replace("Blah Blah 123","Whatever")

My problem is the "123" part might be different from line to line, but I still need to delete the entire line. So I still need to delete this line:

Blah Blah 456

But my PowerShell wouldn't see that.

I can point it at just the "Blah Blah" part, but then it only replaces that part, leaving the "456" behind.

Does PowerShell have a way to handle this? I was thinking of maybe getting the character location (like an array?) of the first character of the line, and then getting a substring from there until a new line character. But I'm not sure that's even possible...

Upvotes: 0

Views: 1938

Answers (2)

TheMadTechnician
TheMadTechnician

Reputation: 36277

Ok, different answer for a different approach. You could use a RegEx replace to replace any given line in a multi-line string based on matching text in that line. We'll use a look behind to find either the beginning of the string or a line break, then any text up to the desired string we're searching for, and any additional characters including the next line break, and if that pattern is found it simply replaces it with nothing. I will create a here-string to simulate a multi-line string like your file input, which includes the key phrase on the first line, a line in the middle, and the last line, just to show it works on any line. Then the replace that actually removes the text.

# Simulate reading a file as a multi-line string (Get-Content -Raw)
$MyArray = @'
Some Chupacabra make great pets
Some Dogs make great pets
Some Cats make great pets
Some Chupacabra make great pets
Some Hamsters make great pets
Some Chupacabra make great pets
'@
# This line will remove any line that has 'Chupracabra' anywhere in the line
$MyArray -replace '(?m)(?<=^|[\r\n]).*?Chupacabra.*?(?:[\r\n]|$)+'

That will produce:

Some Dogs make great pets
Some Cats make great pets
Some Hamsters make great pets

Upvotes: 1

TheMadTechnician
TheMadTechnician

Reputation: 36277

If what you want to do is remove lines entirely that meet a certain criteria I would use the -notmatch operator inside a Where{} statement. For example:

$MyArray = 'Dogs make great pets','Cats make great pets','Chupacabra make great pets','Hamsters make great pets'
$Pets = $MyArray | Where{ $_ -notmatch 'Chupacabra' }

At this point $Pets contains the strings:

Dogs make great pets
Cats make great pets
Hamsters make great pets

Upvotes: 3

Related Questions