在 Powershell 中将内容插入文本文件 [英] Insert Content into Text File in Powershell
问题描述
我想在 Powershell 中将内容添加到文本文件的中间.我正在搜索特定模式,然后在其后添加内容.请注意,这是在文件的中间.
I want to add content into the middle of a text file in Powershell. I'm searching for a specific pattern, then adding the content after it. Note this is in the middle of the file.
我目前拥有的是:
(Get-Content ( $fileName )) |
Foreach-Object {
if($_ -match "pattern")
{
#Add Lines after the selected pattern
$_ += "`nText To Add"
}
}
} | Set-Content( $fileName )
然而,这行不通.我假设是因为 $_ 是不可变的,还是因为 += 运算符没有正确修改它?
However, this doesn't work. I'm assuming because $_ is immutable, or because the += operator doesn't modify it correctly?
将文本附加到 $_ 的方法是什么,这将反映在以下 Set-Content 调用中?
What's the way to append text to $_ that will be reflected in the following Set-Content call?
推荐答案
只输出额外的文本,例如
Just output the extra text e.g.
(Get-Content $fileName) |
Foreach-Object {
$_ # send the current line to output
if ($_ -match "pattern")
{
#Add Lines after the selected pattern
"Text To Add"
}
} | Set-Content $fileName
您可能不需要额外的n",因为 PowerShell 将为您行终止每个字符串.
You may not need the extra ``n` since PowerShell will line terminate each string for you.
这篇关于在 Powershell 中将内容插入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!