PowerShell найти и заменить текст в каждом файле с определенным соответствием и расширением - PullRequest
0 голосов
/ 02 февраля 2019

Я пытаюсь сделать две вещи.Во-первых, я должен удалить весь текст после совпадения, а во-вторых, заменить строку совпадения новым текстом.

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

1 Ответ

0 голосов
/ 02 февраля 2019

Используя регулярное выражение, следующий код должен работать:

$filesPath       = 'c:\temp'
$replaceFile     = 'c:\temp\replaceWithThis.txt'
$regexToFind     = '(?sm)(List of animals(?:(?!List).)*)'
$replaceWithThis = (Get-Content -Path $replaceFile -Raw).Trim()

Get-ChildItem -Path $filesPath -Filter *.txt | ForEach-Object {
    $content = $_ | Get-Content -Raw
    if ($content -match $regexToFind) {
        Write-Host "Replacing text in file '$($_.FullName)'"
        $_ | Set-Content -Value ($content -replace $matches[1].Trim(), $replaceWithThis) -Force
    }
}

Regex Details

(                      Match the regular expression below and capture its match into backreference number 1
   List of animals     Match the characters “List of animals” literally
   (?:                 Match the regular expression below
      (?!              Assert that it is impossible to match the regex below starting at this position (negative lookahead)
         List          Match the characters “List” literally
      )
      .                Match any single character
   )*                  Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...