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"
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With