Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add-Content - append to specific line

Tags:

powershell

I want to add text into specific line of txt file. I can't find any solution on internet.

This code adds text in further line (I want for example second line):

$test_out = "test"

$test_out | Add-Content "C:\tmp\test.txt"
like image 819
charles Avatar asked Aug 12 '15 06:08

charles


People also ask

How do you append to a specific line in Python?

Open the file in append mode ('a'). Write cursor points to the end of file. Append '\n' at the end of the file using write() function. Append the given line to the file using write() function.


2 Answers

If you want to add text to the end of a specific line, you can do it like this

$fileContent = Get-Content $filePath
$fileContent[$lineNumber-1] += $textToAdd
$fileContent | Set-Content $filePath

If you want to replace the text instead of adding, just remove the '+' sign. You do of course have to set the variables $filePath, $textToAdd and $lineNumber first.

like image 65
Erik Blomgren Avatar answered Oct 04 '22 23:10

Erik Blomgren


Here a solution which reads the content of the file and access the line using the array index (-1). This example adds the line test and a line break to the second line.

$filePath = 'C:\tmp\test.txt'
$test_out = "test"

$fileContent = Get-Content -Path $filePath
$fileContent[1] = "{0}`r`n{1}" -f $test_out, $fileContent[1]

$fileContent | Set-Content $filePath
like image 40
Martin Brandl Avatar answered Oct 04 '22 22:10

Martin Brandl