Copying and pasting text to another file is a common thing
to do, copy and paste done. Boom!
In PowerShell scripting copying and pasting text from one
file to another dynamically isn’t as easy as it is done in a spreadsheet or document. Dynamically while the code is running and doing things in the background without human intervention.
As the odds say, if there’s a will there’s a way. And making things
efficient and easy is a good way in life.
If ever a scenario occurs that you need to copy text or
lines in a file from one file to another, without breaking the code execution. Script below works just fine. Just insert the code where it is needed.
PowerShell code snippet to add lines anywhere on the text file, whether at the top, end or at the middle.
#================================
$reader = [System.IO.File]::OpenText("D:\test-read-paste\main1.txt")
#get-content can also be used
$lineNumberx = 3 #adjust this number
where you need to start inserting the text
#Loop
line by line and process
while($null
-ne ($line
= $reader.ReadLine())) {
$textToAdd
= $line
$newLineToAdd
= "`n" #line feed
$fileContent
= Get-Content
'd:\test-read-paste\main2.txt'
$fileContent[$lineNumberx-1] += $newLineToAdd
#$fileContent
| Set-Content d:\test-read-paste\main2.txt
#$fileContent
= Get-Content 'd:\test-read-paste\main2.txt'
$fileContent[$lineNumberx-1] += $textToAdd
$fileContent
| set-Content
d:\test-read-paste\main2.txt
$lineNumberx
= $lineNumberx
+ 1
}
#================================
Main-1 Text file: (sample text only - reference file)
Main-2 Text file (After Inserting Data or after running the PowerShell script)
================================
Free Android Apps:
Click links below to find out more:
Excel Keyboard guide:
Heaven's Dew Fall Prayer app for Android :
Catholic Rosary Guide for Android:
Comments
Post a Comment