Я пытаюсь сделать две вещи.Во-первых, я должен удалить весь текст после совпадения, а во-вторых, заменить строку совпадения новым текстом.
В моем примере ниже я хочу найти строку Список животных и заменить все строки, следующие за ней.во всех документах *. 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