Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - Insert string in text file on the next line after another string

Tags:

powershell

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

like image 581
Conan1989 Avatar asked Oct 20 '22 10:10

Conan1989


1 Answers

# 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
like image 134
David Brabant Avatar answered Nov 03 '22 03:11

David Brabant