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"
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"
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
r
n{1}" -f $test_out, $fileContent[1]
r
n{0}"
"{0}`r`n{1}" -f
is called the format operator, and it replaces {0} and {1} in the string with the subsequent values $test_out
and $fileContent[1]
. It's a lot like how printf
works in other languages.