user1442336
user1442336

Reputation: 55

Powershell -- replace string from one file into another

I have two files; A and B. They both contain similar text but of course there are subtle differences in each.

I need to replace a single line of text from file B that came from File A, leaving all the rest of the text in file B as is. The thing is that I don't know the full line of text that will exist in file A, just the first few letters.

Said another way:

I can get the single line of text(string) from file A: $a = (get-content $original_file)[5]

how do I replace line 5 of file B with what's in variable $A

thanks!

Upvotes: 0

Views: 316

Answers (1)

Keith Hill
Keith Hill

Reputation: 202062

PowerShell arrays are zero-based so line 5 would be index 4. The rest of the script would be something like:

$b = (get-content $another_file)
$b[4] = $a
$b | Out-File -Encoding Ascii $another_file

You can pick Ascii or Unicode (or UTF8) for the encoding.

Upvotes: 1

Related Questions