2016-03-01 3 views
0

У меня есть список.lst, содержащий тысячи строк. Мне нужно заменить одну строку, динамически меняющуюся, и позиция с конца и начало файла также меняется. Но существует постоянная строка «a», «a» (есть несколько из них, мне нужен последний), из которых, если я поеду ниже на две строки, я могу найти цель строку, которую нужно обмануть.Powershell. Замените следующую строку после сопоставления

$log = 'c:\rep\listing.lst' 
$match = '"a","a"' 
$string = Select-String $match $log | ForEach-Object {$_.LineNumber + 1} | Select-Object -Last 1 
(Get-Content $log)[$string] 

Я был в состоянии найти эту строку, но не могу понять, как я могу изменить это цель строку, например «„на“»

ответ

0

Вот функция, я построю некоторое время назад, чтобы найти и заменить строки в текстовых файлах. Как минимум, перейдите в FilePath, строку, которую вы хотите найти, и строку, чтобы заменить ее, и вы золотой:

Find-InTextFile -FilePath C:\MyFile.txt -Find '"a","a"' -Replace 'on' 

function Find-InTextFile 
{ 
    <# 
    .SYNOPSIS 
     Performs a find (or replace) on a string in a text file or files. 
    .EXAMPLE 
     PS> Find-InTextFile -FilePath 'C:\MyFile.txt' -Find 'water' -Replace 'wine' 

     Replaces all instances of the string 'water' into the string 'wine' in 
     'C:\MyFile.txt'. 
    .EXAMPLE 
     PS> Find-InTextFile -FilePath 'C:\MyFile.txt' -Find 'water' 

     Finds all instances of the string 'water' in the file 'C:\MyFile.txt'. 
    .PARAMETER FilePath 
     The file path of the text file you'd like to perform a find/replace on. 
    .PARAMETER Find 
     The string you'd like to replace. 
    .PARAMETER Replace 
     The string you'd like to replace your 'Find' string with. 
    .PARAMETER UseRegex 
     Use this switch parameter if you're finding strings using regex else the Find string will 
     be escaped from regex characters 
    .PARAMETER NewFilePath 
     If a new file with the replaced the string needs to be created instead of replacing 
     the contents of the existing file use this param to create a new file. 
    .PARAMETER Force 
     If the NewFilePath param is used using this param will overwrite any file that 
     exists in NewFilePath. 
    #> 
    [CmdletBinding(DefaultParameterSetName = 'NewFile')] 
    param (
     [Parameter(Mandatory = $true)] 
     [ValidateScript({ Test-Path -Path $_ -PathType 'Leaf' })] 
     [string[]]$FilePath, 

     [Parameter(Mandatory = $true)] 
     [string]$Find, 

     [Parameter()] 
     [string]$Replace, 

     [Parameter()] 
     [switch]$UseRegex, 

     [Parameter(ParameterSetName = 'NewFile')] 
     [ValidateScript({ Test-Path -Path ($_ | Split-Path -Parent) -PathType 'Container' })] 
     [string]$NewFilePath, 

     [Parameter(ParameterSetName = 'NewFile')] 
     [switch]$Force 
    ) 
    begin 
    { 
     $SystemTempFolderPath = Get-SystemTempFolderPath 
     if (!$UseRegex.IsPresent) 
     { 
      $Find = [regex]::Escape($Find) 
     } 
    } 
    process 
    { 
     try 
     { 
      Write-Log -Message "$($MyInvocation.MyCommand) - BEGIN" 
      foreach ($File in $FilePath) 
      { 
       if ($Replace) 
       { 
        if ($NewFilePath) 
        { 
         if ((Test-Path -Path $NewFilePath -PathType 'Leaf') -and $Force.IsPresent) 
         { 
          Remove-Item -Path $NewFilePath -Force 
          (Get-Content $File) -replace $Find, $Replace | Add-Content -Path $NewFilePath -Force 
         } 
         elseif ((Test-Path -Path $NewFilePath -PathType 'Leaf') -and !$Force.IsPresent) 
         { 
          Write-Warning "The file at '$NewFilePath' already exists and the -Force param was not used" 
         } 
         else 
         { 
          (Get-Content $File) -replace $Find, $Replace | Add-Content -Path $NewFilePath -Force 
         } 
        } 
        else 
        { 
         (Get-Content $File) -replace $Find, $Replace | Add-Content -Path "$File.tmp" -Force 
         Remove-Item -Path $File 
         Rename-Item -Path "$File.tmp" -NewName $File 
        } 
       } 
       else 
       { 
        Select-String -Path $File -Pattern $Find 
       } 
      } 
      Write-Log -Message "$($MyInvocation.MyCommand) - END" 
     } 
     catch 
     { 
      Write-Log -Message "Error: $($_.Exception.Message) - Line Number: $($_.InvocationInfo.ScriptLineNumber)" -LogLevel '3' 
      Write-Log -Message "$($MyInvocation.MyCommand) - END" 
      $false 
     } 
    } 
} 
Смежные вопросы