none
Replace a line in 1.txt with a line in 2.txt RRS feed

  • Question

  • Hi everyone, first sory for my bad English

    I need replace a line in 1.txt by a line in 2.txt

    i use

     (get-content -path "2.txt") | foreach-object {$_ -replace (get-content 2.txt -totalcount 2)[-1], (get-content 1.txt -totalcount 2)[-1]} | set-content -path "2.txt"

    but it not work, if i use

    (get-content -path "2.txt") | foreach-object {$_ -replace "Word_IN_2.txt", (get-content 1.txt -totalcount 2)[-1]} | set-content -path "2.txt"

    so it work. where is my mistake? thanks for reading

    • Moved by Bill_Stewart Wednesday, December 12, 2018 5:14 PM Abandoned
    Thursday, August 16, 2018 3:40 AM

All replies

  • Which line needs to be replaced?


    \_(ツ)_/

    Thursday, August 16, 2018 4:42 AM
  • If the latter works, it means that the output of (get-content 2.txt -totalcount 2)[-1] is not equal to "Word_IN_2.txt"

    If you know the line numbers that you want to replace, how about this:

    $File1 = Get-Content -Path 1.txt
    $File2 = Get-Content -Path 2.txt
    
    # Replace line 2 of $File1 with line 2 of $File2 and output to 3.txt
    $File1.Replace($File1[1], $File2[1]) | Out-File 3.txt
    
    

    Thursday, August 16, 2018 4:46 AM
  • To replace any line just replace the line

    $f1 = Get-Content 1.txt 
    $f2 = Get-Content 2.txt
    
    $f2[1] = $f1[1]
    $f2 | Out-File 2.txt
    

    Replacing a whole line never requires a "replace" method.  The replace method above will not work.


    \_(ツ)_/

    Thursday, August 16, 2018 5:00 AM
  • Please provide contents of 1.txt and 2.txt and examples of replacement contents that you want.
    My interpretation is here:

    1.txt
    -------
    apple
    banana
    grape

    2.txt
    -------
    banana
    potato

    result(3.txt)
    -------------
    apple
    potato
    grape

    # Script
    set-location d:\temp # this folder contains 1.txt and 2.txt
    $Search  = (Get-Content .\2.txt)[0] # First line word
    $Replace = (Get-Content .\2.txt)[1] # Second line word
    
    $Result = (get-content .\1.txt) | %{$_ -replace $Search,$Replace}
    
    Write-Host $Result # show result
    
    $Result | Out-file .\3.txt
    



    Thursday, August 16, 2018 6:40 AM