none
[Powershell] overwrite a specific line RRS feed

  • Question

  • Hello,

    I`m just getting startet with Powershell and now I`ll have a question.

    Is it possible to overwrite a specific line in a textfile with Powershell. I´ll need to overwrite

    line 17. Is this possible with Powershell?

    Tuesday, August 3, 2010 5:53 AM

Answers

  • Hi,

    Sure you can.

    # File to change
    $file = c:\myFile.txt
    
    # Get file content and store it into $content variable
    $content = Get-Content -Path $file
    
    # Replace the line number 4 by a new text
    $content[3] = 'new text'
    
    # Set the new content
    $content | Set-Content -Path $file
    
    
    

    If file was formated has the fllowing :
    line 1
    line 2
    line 3
    line 4
    line 5

    The result will be :
    line 1
    line 2
    line 3
    new text
    line 5

    Hope this helps.

     


    Grégory Schiro - PowerShell MVP - PowerShell & MOF
    • Proposed as answer by Grégory Schiro Tuesday, August 3, 2010 8:15 AM
    • Marked as answer by Hanz99 Tuesday, August 3, 2010 9:22 AM
    Tuesday, August 3, 2010 8:15 AM

All replies

  • Hi,

    Sure you can.

    # File to change
    $file = c:\myFile.txt
    
    # Get file content and store it into $content variable
    $content = Get-Content -Path $file
    
    # Replace the line number 4 by a new text
    $content[3] = 'new text'
    
    # Set the new content
    $content | Set-Content -Path $file
    
    
    

    If file was formated has the fllowing :
    line 1
    line 2
    line 3
    line 4
    line 5

    The result will be :
    line 1
    line 2
    line 3
    new text
    line 5

    Hope this helps.

     


    Grégory Schiro - PowerShell MVP - PowerShell & MOF
    • Proposed as answer by Grégory Schiro Tuesday, August 3, 2010 8:15 AM
    • Marked as answer by Hanz99 Tuesday, August 3, 2010 9:22 AM
    Tuesday, August 3, 2010 8:15 AM
  • Works Great, Thx Grégory Schiro.

    Greetz Hanz

    Tuesday, August 3, 2010 9:21 AM