问题描述
我想在 Powershell 中将内容添加到文本文件的特定位置.我尝试使用添加内容,但它在文件末尾添加文本.
I want to add content into the specific place of a text file in Powershell.I tried with Add Content but it is adding text at the end of the file.
推荐答案
这是您可以执行此操作的一种方法.基本上只是将整个文件存储在一个变量中,然后遍历所有行以查找在哪里要插入新的文本行(在我的情况下,我根据搜索来确定这一点标准).然后将新文件输出写回文件,覆盖它:
Here's one way you could do this. Basically just store the entire file in a variable, and then loop through all of the lines to find where you want to insert the new line of text (in my case I'm determining this based off of search criteria). Then write that new file output back to the file, overwriting it:
$FileContent =
Get-ChildItem "C:\temp\some_file.txt" |
Get-Content
$FileContent
<#
this is the first line
this is the second line
this is the third line
this is the fourth line
#>
$NewFileContent = @()
for ($i = 0; $i -lt $FileContent.Length; $i++) {
if ($FileContent[$i] -like "*second*") {
# insert your line before this line
$NewFileContent += "This is my newly inserted line..."
}
$NewFileContent += $FileContent[$i]
}
$NewFileContent |
Out-File "C:\temp\some_file.txt"
Get-ChildItem "C:\temp\some_file.txt" |
Get-Content
<#
this is the first line
This is my newly inserted line...
this is the second line
this is the third line
this is the fourth line
#>
在上面的示例中,我对特定行使用以下条件测试来测试是否应插入新行:
In my example above, I'm using the following conditional test for a particular line to test whether or not the new line should be inserted:
$FileContent[$i] -like "*second*"
这篇关于将内容插入到 Powershell 文本文件中的特定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!