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

Conan1989
  • 328
  • 1
  • 4
  • 8

1 Answers1

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
David Brabant
  • 41,623
  • 16
  • 83
  • 111
  • Beware, if it is a regex and it matches more elements, the index of returns -1. In that case, use ($lines -match "myregex")[0] – Santhos Jan 22 '16 at 13:12
  • 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. – JeffR Jun 15 '16 at 20:25
  • @Santhos why is this a regex and not a powershell builtin function match? Maybe behind the hood it is regex. – Timo Dec 19 '20 at 09:46
  • With **newlines** you build the string, so the **,** is the string concatenator? – Timo Dec 19 '20 at 09:47
  • 1
    @Timo Exactly, behind the hood it is a regex. See https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7.1#matching-operators – Santhos Jan 04 '21 at 19:32