Add-Content - append to specific line

前端 未结 2 1199
既然无缘
既然无缘 2020-12-20 22:46

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):

相关标签:
2条回答
  • 2020-12-20 23:24

    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.

    0 讨论(0)
  • 2020-12-20 23:32

    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
    
    0 讨论(0)
提交回复
热议问题