简体   繁体   English

Powershell —将字符串从一个文件替换为另一个文件

[英]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. A和B。它们都包含相似的文本,但是两者之间当然存在细微的差异。

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. 我需要替换文件B中来自文件A的一行文本,而将其余所有文本保留在文件B中。 The thing is that I don't know the full line of text that will exist in file A, just the first few letters. 事实是,我不知道文件A中将存在的完整文本行,只是前几个字母。

Said another way: 换句话说:

I can get the single line of text(string) from file A: $a = (get-content $original_file)[5] 我可以从文件A中获得一行文本(字符串):$ a =(获取内容$ original_file)[5]

how do I replace line 5 of file B with what's in variable $A 如何用变量$ A中的内容替换文件B的第5行

thanks! 谢谢!

PowerShell arrays are zero-based so line 5 would be index 4. The rest of the script would be something like: PowerShell数组基于零,因此第5行将是索引4。脚本的其余部分将类似于:

$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. 您可以选择Ascii或Unicode(或UTF8)作为编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM