How do I insert a new line into a file at a line position using PowerShell?

Viewed 1348

I'm relatively new to PowerShell. I would like to be able to insert a line of text into a file by line position.

I've seen several examples how to do this via searching for line contents. I haven't been able to find one that does it by line position.

How would I do this in PowerShell script?

Thanks,JohnB

3 Answers

Provided there are no memory issues with reading in the entire text file, you can read your file data as a list and then use the Insert() method.

$file = (Get-Content file.txt) -as [Collections.ArrayList]
$file.Insert(3,'inserted text') # Line 3 starting from 0
$file | Set-Content file.txt

You could read the entire file into an array and then "split" it at the position where you want to insert a new line:

$filePath = '.\path\to\file'
$newLine = "This is the line we want to insert"
$lineIndex = 3 

# Read original content line-by-line
$originalContent = Get-Content $filePath

# Split into the lines before and after the index we want to insert at
$precedingLines = $originalContent[0..($lineIndex - 1)]
$succeedingLines = $originalContent[$lineIndex..($originalContent.Length - 1)]

# Insert our new line in between, wrap in a new array and pipe to Set-Content
@($precendingLines; $newLine; $succeedingLines) |Set-Content $filePath

Since array indices are 0-based, this will insert $newLine as the 4th line from the top

If the file is large, you can use switch to insert a new line like below.
This does not involve splitting and recombining arrays; it simply reads the file line-by-line into a variable and if the insert position is reached, it outputs both the line to insert and the line read from the file.

$filePath         = 'D:\Test\file.txt'
$textToInsert     = 'This line is inserted'
$positionToInsert = 3  # insert the line at position (1..N)
$currentline      = 0  # initialize a current line counter

$newContent = switch -File $filePath {
    default {
        $currentline++
        if ($currentline -eq $positionToInsert) { $textToInsert }
        $_
    }
}

Set-Content -Path $filePath -Value $newContent
Related