【发布时间】:2019-06-26 21:46:12
【问题描述】:
我正在尝试做两件事。首先我要在匹配后删除所有文本,然后用新文本替换匹配行。
在下面的示例中,我想找到行 List of animals 并将所有文档 *.txt 中的所有行替换为 中的文本replaceWithThis.txt.
我下面的第一个 foreach 将删除 动物列表 之后的所有内容,我的第二个 foreach 将替换 动物列表 并因此在该行之后添加新内容replaceWithThis.txt。
replaceWithThis.txt 包含:
List of animals
Cat 5
Lion 3
Bird 2
*.txt 包含:
List of cities
London 2
New York 3
Beijing 6
List of car brands
Volvo 2
BMW 3
Audi 5
List of animals
Cat 1
Dog 3
Bird 7
代码:
$replaceWithThis = Get-Content c:\temp\replaceWithThis.txt -Raw
$allFiles = Get-ChildItem "c:\temp" -recurse | where {$_.extension -eq ".txt"}
$line = Get-Content c:\temp\*.txt | Select-String cLuxPlayer_SaveData | Select-Object -ExpandProperty Line
foreach ($file in $allFiles)
{
(Get-Content $file.PSPath) |
ForEach-object { $_.Substring(15, $_.lastIndexOf('List of animals')) } |
Set-Content $file.PSPath
}
foreach ($file in $allFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object { $_ -replace $line,$replaceWithThis } |
Set-Content $file.PSPath
}
所有(*.txt)的最终结果应该是:
List of cities
London 2
New York 3
Beijing 6
List of car brands
Volvo 2
BMW 3
Audi 5
List of animals
Cat 5
Lion 3
Bird 2
【问题讨论】:
标签: powershell replace foreach