【问题标题】:Replace only digit in a specific line of text file仅替换特定行文本文件中的数字
【发布时间】:2021-07-10 17:12:13
【问题描述】:

我有一个像这样具有唯一 IP 的文本文件

172.21.2.15|3
172.33.3.45|6
172.15.12.5|2

我需要根据IP找到特定的行,然后将分隔符后面的数字替换为当前值加一。

到目前为止,我只能以这种方式找到该行

$client = "172.33.3.45"
$line = gc C:\myfile.txt | select-string $client | Select-Object -ExpandProperty Line

但即使我已经进行了几次搜索,我也不知道如何进行替换。

如何在文件中为该 IP 的数字加 1?

【问题讨论】:

    标签: regex powershell replace


    【解决方案1】:

    试试这个:

    $IPToFind='172.33.3.45'
    $File=C:\myfile.txt
    
    $Contentcsv=import-csv $File -Delimiter '|' -Header IP, ID
    $Contentcsv | %{if($_.IP -eq $IPToFind){$_.ID=[int]$_.ID+1}; "{0}|{1}" -f $_.IP, $_.ID} | Out-File $File
    

    如果你想要更多解释:

    $IPToFind='172.33.3.45'
    
    $Contentcsv=import-csv "C:\temp\test.txt" -Delimiter '|' -Header IP, ID
    $Contentcsv | Foreach{
    
        #modify value if IP is founded
        if($_.IP -eq $IPToFind)
        {
        $_.ID=[int]$_.ID+1
        }; 
    
        #send tou output with -f (-format operator)
        "{0}|{1}" -f $_.IP, $_.ID
    
    } | Out-File "C:\temp\test.txt"
    

    【讨论】:

    • 非常感谢,我自己永远做不到。现在我什至尝试理解你的代码。再次感谢。
    • 提示是import-csv。您可以指定标题
    【解决方案2】:

    这是不使用任何循环的替代方法:

    using namespace System.Text.RegularExpressions
    
    [string] $IP = "172.33.3.45"
    $Data = Get-Content $pwd\address.txt -Raw
    
    [regex] $Client = "(?<ip>" + [regex]::Escape($IP) + "\|)(?<digit>\d+)"
    
    $Evaluator = {
        param($Match)
    
        [string] $Value = $Match.Groups["digit"].Value
        $Match.Groups["ip"].Value + ([System.Int32]::Parse($Value) + 1)
    }
    
    [regex]::Replace($Data, $Client, $Evaluator, [RegexOptions]::Multiline) |
    Out-File $pwd\updated.txt
    

    【讨论】:

      【解决方案3】:

      由于我们都在这里发挥创造力,并且根据 op 评论,OP 似乎迷失在有用的有用答案中......

      “现在我什至试着理解你的代码。”

      ...

      这是一种替代方法,不使用任何导入、循环、自定义格式、速记/别名等。

      • 使用 PSScriptAnalyzer 检查您的 PowerShell 代码以获得最佳实践

      http://mikefrobbins.com/2015/11/19/using-psscriptanalyzer-to-check-your-powershell-code-for-best-practices

      当您的编码/开发工具警告您脚本/功能/模块等中的错误时(考虑哪些别名),那么,您就知道了。

      • 别名的最佳做法

      https://devblogs.microsoft.com/scripting/best-practice-for-using-aliases-in-powershell-scripts

      https://devblogs.microsoft.com/scripting/using-powershell-aliases-best-practices

      嘿,但这完全取决于选择。

      ;-}

      以及,希望所有技能水平的通俗英语,因此,可能更容易阅读和理解,没有需要弄清楚的过于神秘的东西,并且无需进一步的长期护理和喂养解释,对于那些 稍后查看/分享。

      ;-}

      .DESCRIPTION
         Given a text file with custom formatted IPAddresses. Read the content and 
         increment the last digit in the custom IPAddress
      
      .EXAMPLE
         .\Edit-IPAddressList.ps1
      
          # Results
      
          VERBOSE: 
          *** Environment initialization ***
      
      
          *** Collecting content for modification ***
      
          172.21.2.15|3
          172.33.3.45|6
          172.15.12.5|2
      
          *** Building replacement content ***
      
      
          *** Writing replacement content to current file ***
      
          VERBOSE: Performing the operation "Set Content" on target "Path: D:\Temp\IPList.txt".
          VERBOSE: Performing the operation "Clear Content" on target "Item: D:\Temp\IPList.txt".
      
          *** Modification results ***
      
          172.21.2.15|3
          172.33.3.45|7
          172.15.12.5|2
      
      
      
      .INPUTS
         Full file path to the IPAddress files
      
      .OUTPUTS
         Updates IPAddress files without the need for new files
      
      .NOTES
         Leveraging nested variables to combine results for specific results per file
         read.
      
      .COMPONENT
         None - stand alone
      
      .ROLE
         File operations. 
      
      .FUNCTIONALITY
         Updating file content specifics for required use cases.
         The regular expressions are used to supply and parse text.
      
         '\|'          = split the string at the pipe
         '.*Path\s|\}' = remove uneeded string content 
         [1]           = get the array position from a split
         [int          = Setting data type for math needs
      #>
      
      Clear-Host
      
      Write-Verbose -Message "`n*** Environment initialization ***`n" -Verbose
      $FilePath, 
      $SearchString, 
      $StringSplit,
      $ReplacementPattern = 'D:\Temp\IPList.txt', 
                            '172.33.3.45', 
                            '\|', 
                            '.*Path\s|\}'
      
      Write-Host "`n*** Collecting content for modification ***`n" -ForegroundColor Yellow
      
      Get-Content -Path $FilePath
      
      Write-Host "`n*** Building replacement content ***`n" -ForegroundColor Yellow
      
      $ReplacementContent = ((($FindSearchString = (Get-Content -Path $FilePath) -match $SearchString) -Split $StringSplit)[1]), 
                            ([int](($FindSearchString -Split $StringSplit)[1]) + 1)
      
      Write-Host "`n*** Writing replacement content to current file ***`n" -ForegroundColor Yellow
      
      (Get-Content -Path $FilePath) -replace $ReplacementContent | 
      Set-Content -Path ($FilePath -replace $ReplacementPattern) -Verbose
      
      Write-Host "`n*** Modification results ***`n" -ForegroundColor Yellow
      
      Get-Content -Path $FilePath
      

      注意:不需要Write-Host 的东西。它只是为了这篇文章和 真的应该删除。

      那些Write-Verboseverbose 和开头和结尾都不是 Get-Content 行。

      基于注释的帮助块是可选的,但它是一个谨慎的部分,以避免 代码以避免代码行中不需要的 cmets。

      那么,就这样吧:

      Clear-Host
      $FilePath, $SearchString, $StringSplit,
      $ReplacementPattern = 'D:\Temp\IPList.txt', '172.33.3.45', '\|', '.*Path\s|\}'
      
      $ReplacementContent = ((($FindSearchString = (Get-Content -Path $FilePath) -match $SearchString) -Split $StringSplit)[1]), 
                            ([int](($FindSearchString -Split $StringSplit)[1]) + 1)
      
      (Get-Content -Path $FilePath) -replace $ReplacementContent | 
      Set-Content -Path ($FilePath -replace $ReplacementPattern)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-02
        • 1970-01-01
        • 2017-11-03
        • 2014-05-20
        • 1970-01-01
        • 2014-06-21
        相关资源
        最近更新 更多