5

This seems like a simple one, but I just can't wrap my head around it / find a post covering it

I'm trying to use PowerShell to modify a text (config) file Find where a specific string (A) occurs, then add another string (B) to the next line after. Preserving the line where string (A) occurs

So the problem is I can't do a simple find and replace as the line where string (A) occurs has other text after it

Here's for hoping someone smarter than I knows the trick. Cheers

2
  • Same question at stackoverflow.com/questions/1875617/… and excellent answer by @Keith Hill Commented Apr 17, 2014 at 11:23
  • @David Brabant's answer is even neater Commented Jan 22, 2016 at 12:40

1 Answer 1

4
# Let's say my file test.txt contains
# Line1
# Line2
# Line3
# Line4

$lines = Get-Content test.txt
$pos = [array]::indexof($lines, $lines -match "Line3") # Could use a regex here
$newLines = $lines[0..($pos -1)], "MyNewLine3", $lines[$pos..($lines.Length - 1)]

$newLines | Set-Content test.txt
Sign up to request clarification or add additional context in comments.

5 Comments

Beware, if it is a regex and it matches more elements, the index of returns -1. In that case, use ($lines -match "myregex")[0]
Also beware that for doing the string matches if the file has empty rows and the call doesn't match any rows it will return the index of the first empty row.
@Santhos why is this a regex and not a powershell builtin function match? Maybe behind the hood it is regex.
With newlines you build the string, so the , is the string concatenator?
@Timo Exactly, behind the hood it is a regex. See learn.microsoft.com/en-us/powershell/module/…

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.