Reputation: 13
I need to copy line 11 from file Data1.txt and copy the line 11 contents to file Data2.txt to line 11 without overwriting all the file.
This overwrites Data2 file with line 11 only, not sure how to paste the contents to line 11 only.
$Content= Get-Content -Path C:\Desktop\Data1.txt
$Content= $Content[10]
Set-Content -Path C:\Desktop\Data2.txt -Value $Content
This replaces Data2 file with Data1 contents
$Content= 'C:\Desktop\Data1.txt'
(Get-Content C:\Desktop\Data2.txt) -replace 'condition=$' | Set-Content $Content
Upvotes: 1
Views: 739
Reputation: 15488
Try this:
$Content= Get-Content -Path C:\Desktop\Data1.txt
$Contentp = $Content[10]
$Line = 0
Get-Content C:\Desktop\Data2.txt | ForEach {
$Line++
If ($Line -eq 11) {
$Contentp
}
Else {
$_
}
} | Set-Content C:\Data\Data2.txt
Set-Content overwrites text content. Here we are reading each line of file using ForEach loop increment line counter. When line is 11 we place the line to paste. Else the original line is pasted. Then the new content is passed to data2.txt.
Upvotes: 0
Reputation: 61148
If you mean to overwrite line 11 in file Data2.txt with line 11 read from the Data1.txt file, you could go with DevX's helpfull answer.
However, that reads the whole of Data1.txt in memory and without knowing how large that file is, there may be a more memory-friendly approach to that using the TotalCount
parameter:
$copyLineFrom = 'C:\Desktop\Data1.txt'
$fileToUpdate = 'C:\Desktop\Data2.txt'
# get line 11 from Data1.txt
$line11 = Get-Content -Path $copyLineFrom -TotalCount 11 | Select-Object -Last 1
$data = Get-Content -Path $fileToUpdate
# replace line 11 (index 10)
if ($data.Count -ge 11) { $data[10] = $line11 }
$data | Set-Content -Path $fileToUpdate
If you want to insert line 11 from Data1.txt file into the Data2.txt file at position 11 (and thereby moving all lines below that 1 position down), I'd suggest you use a List object and use its Insert()
method:
$copyLineFrom = 'C:\Desktop\Data1.txt'
$fileToUpdate = 'C:\Desktop\Data2.txt'
# get line 11 from Data1.txt
$lineToInsert = Get-Content -Path $copyLineFrom -TotalCount 11 | Select-Object -Last 1
# read Data2.txt in a List object
$data = [System.Collections.Generic.List[string]]::new([string[]](Get-Content -Path $fileToUpdate))
# insert the line at position 11 (index 10)
if ($data.Count -ge 11) { $data.Insert(10, $lineToInsert) }
$data | Set-Content -Path $fileToUpdate
Upvotes: 1
Reputation: 308
You simply have to read the content of the Data2.txt and then set the line 11 to the line 11 of Data 1
$Content1= Get-Content -Path C:\Desktop\Data1.txt
$Content2= Get-Content -Path C:\Desktop\Data2.txt
$Content2[10] = $Content1[10]
Set-Content -Path C:\Desktop\Data2.txt -Value $Content2
This will do the basic job for you but it assumes that you have at least 11 lines in both files. Your other approach is not in my expertise so someone here may be able to help you with that.
Upvotes: 1