我想在Powershell中将内容添加到文本文件的中间。我正在搜索一个特定的模式,然后在它后面添加内容。注意,这是在文件的中间。
我目前拥有的是:
(Get-Content ( $fileName )) |
Foreach-Object {
if($_ -match "pattern")
{
#Add Lines after the selected pattern
$_ += "`nText To Add"
}
}
} | Set-Content( $fileName )
然而,这不起作用。我猜想是因为$_是不可变的,还是因为+=操作符没有正确地修改它?
向$_追加将在下面的Set-Content调用中反映的文本的方法是什么?
发布于 2009-12-10 01:54:06
只需输出额外的文本,例如
(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将为您行终止每个字符串。
发布于 2009-12-12 17:26:55
这样如何:
(gc $fileName) -replace "pattern", "$&`nText To Add" | sc $fileName
我认为这是相当直接的。唯一不明显的是"$&",它指的是与"pattern“匹配的内容。更多信息:http://www.regular-expressions.info/powershell.html
发布于 2012-07-16 19:46:58
这个问题可以通过使用数组来解决。文本文件是字符串数组。每个元素都是一行文本。
$FileName = "C:\temp\test.txt"
$Patern = "<patern>" # the 2 lines will be added just after this pattern
$FileOriginal = Get-Content $FileName
<# create empty Array and use it as a modified file... #>
$FileModified = @()
Foreach ($Line in $FileOriginal)
{
$FileModified += $Line
if ($Line -match $patern)
{
#Add Lines after the selected pattern
$FileModified += 'add text'
$FileModified += 'add second line text'
}
}
Set-Content $fileName $FileModified
https://stackoverflow.com/questions/1875617
复制相似问题