replace string in last line of file

Welcome Forums General PowerShell Q&A replace string in last line of file

This topic contains 4 replies, has 5 voices, and was last updated by

 
Participant
7 months, 3 weeks ago.

  • Author
    Posts
  • #96680

    Participant
    Points: 0
    Rank: Member

    I need to replace the dollar amount in the last line of a file with $a (c:\myFile.txt)
    $a = 1000 replace substring(3,4) replace 0500 with 1000

    file looks like:

    gadfg
    agdaga
    0000500

  • #96687

    Participant
    Points: 59
    Rank: Member

    Please share your code, and the issue/question you have about it.

  • #96743

    Participant
    Points: 9
    Rank: Member

    I think you will need to read the file, make the replacement, then write the file out. Look for a few threads earlier this month on this forum for code examples/solutions.

  • #96747

    Participant
    Points: 13
    Rank: Member

    if 0500 only occurs once in the text file you could try

    (get-content c:\test\replace.txt) | foreach-object {$_ -replace "0500", "1000"} | set-content c:\test\replace.txt

  • #96753

    Participant
    Points: 1
    Rank: Member

    maybe something like this:

    
    $file = @"
    gadfg
    agdaga
    0000500
    "@
    $file | out-file c:\temp\tempfile.txt
    
    $content = get-content c:\temp\tempfile.txt 
    
    $newcontent = $content | select -SkipLast 1
    $newcontent += ($content | select -Last 1) -replace ("0500","1000")
    
    

The topic ‘replace string in last line of file’ is closed to new replies.